Skip to content
Search

C++:static

lastmod 2016-12-18created 2016-04-222 edits

Magic statics

Since C++11, the standard guarantees that construction of local static objects is thread-safe. This feature seems to be called magic statics.

Troubleshooting

Duplicate symbol in static member

Initializing a static member variable inside a header file, as below, causes a duplicate symbol error.

class BaseClass
{
public:
    static std::string bstring;
};
std::string BaseClass::bstring {"."};

When you need to initialize a static member inside a header like this, use a template.

template< class Dummy >
struct BaseClass_statics
{
    static std::string bstring;
};

template< class Dummy >
std::string BaseClass_statics<Dummy>::bstring = ".";

class BaseClass
    : public BaseClass_statics<void>
{};