Oct 19, 2012 at 4:01pm UTC
Hello everyone,
I am trying to create a const std::string in ONLY the class implementation file, and then access it through a static method for the class.
I wrote a little example and put it on gist.
It is seg-faulting when it calls the method in the 'A' class, but not when I call it in the main method.
https://gist.github.com/3918956
Thanks for any help.
EDIT:
NOTE:
The code must be in different files for it to break
Last edited on Oct 19, 2012 at 4:06pm UTC
Oct 19, 2012 at 4:16pm UTC
It worked for me. gcc 4.4.3
Oct 19, 2012 at 4:33pm UTC
Did you use multiple files? It only breaks in multiple files.
Oct 19, 2012 at 4:40pm UTC
FIXED in the main project by something that seemed irrelevant (constructor) but cannot fix in test case.
Oct 19, 2012 at 4:42pm UTC
It SHOULD segfault. The string isn't guaranteed to be created yet. Try instantiating that instance of A in main instead of in the global scope. When you create t in the global scope there is a chance it will be created in the wrong order, as for your case.
Last edited on Oct 19, 2012 at 4:43pm UTC
Oct 19, 2012 at 5:01pm UTC
I confirmed L B's reply. Depending on the order in which I link the object files, the program may run or seg fault.
g++ -o test testB.o test.o creates a program that seg faults.
g++ -o test test.o testB.o creates a program that runs.
Looking at the code, it seems like this is backwards, but the point is that this is unsafe.