c – 模板类中的静态变量初始化

任何人都可以解释为什么这个代码崩溃?

在使用mingw和ubuntu的两个窗口上都有相同的行为.

每个调试器传递给构造函数的参数“a”是“优化的”.

当我尝试访问静态成员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

最佳答案 我相信你在这里有一个
static initialization order fiasco的实例.简而言之,你不能依赖静态初始化器的顺序.您应该考虑在首次使用模式上使用构造(请参阅相同的链接,下面的一个问题).

en.cppreference.com有以下说法:

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.

点赞