gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 02:08:15 25 4
gpt4 key购买 nike

谁能解释为什么这段代码会崩溃?使用 mingw 和 ubuntu 的两个窗口上的行为相同。

每个调试器传递给构造函数 One 的参数“a”被“优化掉”。

当我尝试访问静态成员 two_ 时发生崩溃;

三.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 的实例.简而言之,您不能依赖于静态初始化程序的顺序。您应该考虑使用 construct on first use 模式(参见相同的链接,下面的一个问题)。

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.

关于c++ - 模板类中的静态变量初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38060498/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com