user6519777
user6519777

Reputation: 41

static variable initialization in template class

Can anyone explain why this code is crashing? The same behavior is on both windows with mingw and ubuntu.

Per debugger the parameter "a" passed to constructor One is "optimized out".

The crash happens when I try to access to static member two_;

three.h

#ifndef THREE_H
#define THREE_H
#include <string>

class One
{
public:
    One(const std::string& a)
        : a_(a)
    {

    }
    std::string a_;
};

template<typename P>
class Two : public One
{
public:
    Two()
        : One(P::name)
    {

    }
    std::string foo()
    {
        return a_;
    }
};

template<typename T>
class Three
{
public:
    struct Info
    {
        static std::string name;
    };
    typedef Two<Info> Two_t;
    static Two_t two_;
};

template < typename T >
std::string Three<T>::Info::name = std::string("aaaa");

template < typename T >
typename Three<T>::Two_t Three<T>::two_ = Three<T>::Two_t();


#endif // THREE_H

Upvotes: 4

Views: 290

Answers (1)

md5i
md5i

Reputation: 3073

I believe what you have here is an instance of the static initialization order fiasco. Put simply, you cannot depend on the order of static initializers. You should consider using a construct on first use pattern (see the same link, one question below).

en.cppreference.com has the following to say:

1) Unordered dynamic initialization, which applies only to (static/thread-local) class template data members that aren't explicitly specialized. Initialization of such static variables is indeterminately sequenced with respect to all other dynamic initialization. Initialization of such thread-local variables is unsequenced with respect to all other dynamic initialization.

Upvotes: 2

Related Questions