c++ - 函数,在对象销毁期间调用

标签 c++ destructor

您能否提供反射(reflect)以下规则的代码示例:

N3797 c++14,第 3.6.3/2 节:

If a function contains a block-scope object of static or thread storage duration that has been destroyed and the function is called during the destruction of an object with static or thread storage duration, the program has undefined behavior if the flow of control passes through the definition of the previously destroyed block-scope object.

最佳答案

给你:

void theFunction()
{
  static std::unique_ptr<int> foo { new int(42) };
}

struct Creator
{
  Creator() { theFunction(); }
};


struct Destroyer
{
  ~Destroyer() { theFunction(); }
};

Destroyer d;
Creator c;

int main()
{}

d 首先被创建,但它的构造函数什么也不做。然后,c 被创建,作为其初始化的一部分,theFunction() 被调用,这导致 block 作用域 static-storage-duration 变量 foo 被初始化。

然后,在程序退出时,静态存储对象以相反的构造顺序销毁。所以foo被销毁,然后是c。最后,d 被销毁,但是它的析构函数调用了 theFunction(),这导致控制流再次到达 foo 的定义,在它被销毁之后已经销毁了。

您显示的标准引述将未定义的行为归因于此。

关于c++ - 函数,在对象销毁期间调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24612187/

相关文章:

c++ - 具有函数指针和可变参数模板的 CUDA 内核

c++ - 在 C++ 中,通过指针或实例访问类/结构的优点是什么

PHP - 如何销毁它包含的对象和对象?

c++ - 销毁存储在指针 vector 中的对象

c++ - 在被删除的对象内部动态分配对象会发生什么?

c++ - 析构函数 C++ : type '***' argument given to 'delete' , 预期指针

c++ - 为什么 std::function 不参与重载决策?

c++ - 如何在 C++11 中输出枚举类的值

从文件读取时出现 C++ 访问冲突

c++ - #define a b+c 混淆..我没有得到我预期的输出