gpt4 book ai didi

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

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

您能否提供反射(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/

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