gpt4 book ai didi

c++模板怪异优化

转载 作者:IT老高 更新时间:2023-10-28 22:21:41 25 4
gpt4 key购买 nike

我像 boost 一样写了一个单例模板类:

template <typename _T>
class Singleton
{
public :
static _T* Instance()
{
static _T obj;
return &obj;
}

protected :
Singleton() {}

private :
struct ObjectCreator
{
ObjectCreator()
{
Singleton<_T>::instance();
}
};

static ObjectCreator object_creator;
};

template <typename _T>
typename Singleton<_T>::ObjectCreator Singleton<_T>::object_creator;

我写了 main 函数来测试它。

#include "Singleton.h"
class A : public Singleton <A>
{
public:
int a;
};


int main()
{
A::Instance()->a = 2;
}

我知道我在 ObjectCreator 中输入了错误的实例的构造函数,奇怪的是我可以通过gcc-4.4.7正确编译它,然后我使用clang-6.0,它打错了。

我猜 gcc 可以做一些优化,因为我没有对 ObjectCreator 做任何事情,所以它忽略了错误代码。

我有两个问题:

  1. 我应该怎么做才能让 gcc 向我报告该错误(无需更改我的代码),例如添加一些编译器标志?
  2. 如果有人对此有更可靠的解释?一些官方文档会做。

Ps:我知道 boost 会添加一个 do_nothing ObjectCreate中的函数并从 Singleton<_T>:: Instance() 调用电话以避免这种优化。

最佳答案

  • What should I do to make gcc report that error (without changing my code), like add some compiler flag?

您可以添加显式实例化 template class Singleton<float>; (我只是随机选择 float 作为类型,但您可以选择更合适的类型)强制 GCC 检查语法。见 https://gcc.godbolt.org/z/ii43qX举个例子。

如果您只是想要检查,您还可以通过将另一个 cpp 文件添加到项目中来将此显式实例化到单独的编译单元。

但是,执行显式实例化比隐式实例化更强,因为所有成员和方法都将被实例化。可能需要这种行为(参见标准库的示例)。

  • If anyone has a more reliable explanation for this? Some official doc would do.

静态成员在以需要其定义的方式使用之前不会被隐式初始化(​​这与显式实例化非常不同)。

@StoryTeller 在标准中找到正确的段落

14.7.1 Implicit instantiation [temp.inst]

The implicit instantiation of a class template specialization causes the implicit instantiation of the declarations, but not of the definitions or default arguments, of the class member functions, member classes, static data members and member templates; and it causes the implicit instantiation of the definitions of member anonymous unions. Unless a member of a class template or a member template has been explicitly instantiated or explicitly specialized, the specialization of the member is implicitly instantiated when the specialization is referenced in a context that requires the member definition to exist; in particular, the initialization (and any associated side-effects) of a static data member does not occur unless the static data member is itself used in a way that requires the definition of the static data member to exist.

编辑您应该接受@StoryTeller 的回答,因为他首先正确解释了您问题的两个方面。

关于c++模板怪异优化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52052388/

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