gpt4 book ai didi

c++ - 调用构造函数之前是否初始化了静态成员?

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

我有一个带有 std::map 静态成员的类。我在执行构造函数体之前在同一个翻译单元(同一个 cpp 文件)中初始化它。我的程序没有输出就失败了。我发现了称为静态初始化顺序失败的问题,但我认为情况并非如此。

class Test {
public:
static std::map<std::string, Test*> a;
Test(std::string ID) {
/* in my complete code (where constructor
* implementation and map initialization
* are in a separate Test.cpp file), this fails, maybe
* because the map is not initialized at the time
* the constructor is being called by a sub class of Test */
a.insert({ID, this});
}
};

当我对其他变量进行一些静态初始化时,构造函数由 TestSubclass 调用。有没有在map初始化之前调用Test构造函数的场景?

最佳答案

“有没有之前调用Test的构造函数的场景 map 已初始化?” 当然可以。所需要的只是有是 Test 在其他翻译单元中的静态实例,而不是定义 map 的一个。 (其中构造函数的代码Test 的定义是无关紧要的。重要的是静电在哪里Test 的实例已定义。)

还有其他可能的场景:一些的构造函数例如,其他静态对象使用 Test 的本地实例。

这个问题的通常解决方案是使用工厂方法 map :

std::map<std::string, Test*>& Test::registry()
{
static std::map<std::string, Test*> theOneAndOnly;
return theOneAndOnly;
}

这将导致在第一次需要时构建 map 。

您使用的是哪个编译器?您不能为类定义中的静态成员,除非该成员是 const 且具有整数或枚举类型。

关于c++ - 调用构造函数之前是否初始化了静态成员?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26995310/

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