gpt4 book ai didi

C++ 静态成员在初始化后重新初始化

转载 作者:行者123 更新时间:2023-12-03 06:55:50 24 4
gpt4 key购买 nike

我正在尝试实现“HasUtility”模板类的设计,允许创建模板化静态成员(实用程序)并维护所有实用程序(基类)的列表

代码如下:

StaticUtilityBase.h:

#include <vector>
#include <iostream>

class StaticUtilityBase {
public:
static std::vector<StaticUtilityBase*> all;
StaticUtilityBase() {
all.push_back(this);
printAllState();
}
static void printAllState() {
std::cout << "All size is " << all.size() << ", address is " << &all << std::endl;
}
};

template <typename T> class StaticUtility : public StaticUtilityBase {};

template <typename T> class HasUtility {
public:
static StaticUtility<T> utility;
};

template <typename T> StaticUtility<T> HasUtility<T>::utility;

TemplateUtility.cpp:

#include "StaticUtilityBase.h"
std::vector<StaticUtilityBase*> StaticUtilityBase::all;

和主要的:

#include <iostream>
#include "StaticUtilityBase.h"
class A {};
class B {};
int main() {
std::cout << "Initializations done" << std::endl;
StaticUtilityBase::printAllState();
HasUtility<A>::utility; //Tell to the compiler that the static member is used so the constructor
HasUtility<B>::utility; // of utility is used before main execution, during initializations
}

执行时得到如下结果:

All size is 1, address is 0x562942baa1f0
All size is 2, address is 0x562942baa1f0
Initializations done
All size is 0, address is 0x562942baa1f0

所有尺寸最后应该还是2。看起来“all”在“utility”成员初始化之后被重新初始化了!地址相同,所以我认为它是同一个对象。也许它是从一个空的复制过来的??欢迎任何帮助!

我使用 gcc 和 C++17

最佳答案

您正在从另一个静态对象(在本例中为 StaticUtilityBase::all)的构造函数访问一个静态对象(在本例中为 template <typename T> StaticUtility<T> HasUtility<T>::utility;)。

由于在跨翻译单元的不同静态对象的初始化之间没有顺序保证,因此您尝试执行的操作将行不通。

参见 https://en.cppreference.com/w/cpp/language/siof获取更多信息。

验证这一点的简单方法是将第二个静态对象添加到 StaticUtilityBase它在构建时打印出来: static int printer = []()->int{std::cout << "Initing StaticUtilityBase\n"; return 0;}()

关于C++ 静态成员在初始化后重新初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64612137/

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