On Wed, 06 Jun 2007 08:01:18 +0100
John D Lamb
On Tue, 2007-06-05 at 16:11 -0400, Jerry Feldman wrote:
I have a static string defined in a class: class Foo { public: ... static const std::string default_name; ... };
In the C++ file: const std::string Foo::default_name("standard");
The C++ file is compiled into a shared library, say libfubar.so
The executable is built: segfault in std::string when it is accessing Foo::default_name.
This looks familiar. I had a similar problem a while back. IIRC, the problem only occurs when you build a shared library and have static data members in a class that use heap memory. I think the code
const std::string Foo::default_name("standard");
never gets executed in the shared library, leaving default_name declared but not defined.
Some workarounds (I haven't tested them): 1. Put the definition in the header file rather than the .cpp or .cc file (a version of this worked for me).
2. Use something like the following instead: class Foo { ... public: static std::string const& default_name(); };
std::string const& Foo::default_name(){ static std::string const default_name("standard"); return default_name; } Then you have a data-initialiser. I don't think I've tried this.
My bet, though, is that you've solved this already.
Good ideas. I actually set up a small test case, using my example, and
it worked fine, but I'll take a look at your solution.
Your solution worked fine in the code. I don't know why I didn't think
of it yesterday because I do this elsewhere in the code.
BTW: Sorry for the top posting of my earlier reply :-(.
--
Jerry Feldman