gpt4 book ai didi

c++ - 使无序初始化 statc 有序

转载 作者:太空狗 更新时间:2023-10-29 23:17:25 27 4
gpt4 key购买 nike

以下类使用 CRTP 尝试将类型添加到具有 Schwarz 计数器以确保初始化顺序的 std::vector。根据 3.6.2/2 成员 h_ 具有无序初始化。我将如何更改它以确保它已订购初始化?我希望派生类只需正确地从类继承即可。

#ifndef P_H_
#define P_H_

#include "PR.h"

template <typename T>
class P
{
class helper
{
public:
helper()
{
PR.push_back(typeid(T));
}
};
static helper h_;
};

template <typename T>
typename P<T>::helper P<T>::h_;

#endif

最佳答案

此类问题的标准模式是使用生成器而不是公开全局静态变量。 (这是C++的老问题)

所以改变:

static helper h_ ;

到:

static helper & h_() ;

然后这样定义它:

template <typename T>
typename P<T>::helper & P<T>::h_()
{
static P<T>::helper value_ ;
return value_ ;
}

这样可以保证在使用前进行初始化。

关于c++ - 使无序初始化 statc 有序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18197644/

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