gpt4 book ai didi

c++ - 局部静态对象的静态破坏

转载 作者:行者123 更新时间:2023-11-30 04:28:12 25 4
gpt4 key购买 nike

帮我理解这个……看粗体。来自标准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 blockscope object. Likewise, the behavior is undefined if the block-scope object is used indirectly (i.e., through a pointer) after its destruction.

Manager& GetManager()
{
static Manager localMan;
return localMan;
}

然后在别的地方...

{
static User localUser;
localUser.DoSomething(); //localUser calls GetManager and uses the reference returned.
}

然后在用户析构函数中...

User::~User()
{
GetManager().DoSomethingOneLastTime();
}

//Now lets say Main exits and static destruction begins.
//Somehow localMan is destructed before User.
//Then user calls the GetManager() function in it's destructor.
//What case is this defined, and what case makes this undefined?

标准是说如果使用 odr-use 规则静态创建的本地静态 localMan 对象被破坏,然后再次调用该函数(是否创建新的静态对象)这是未定义的?看起来它为定义的行为留出了空间,但如果它通过了被破坏对象的定义,它就不是。

有人对此有清晰的认识吗?

最佳答案

我相信这里的关键词是

creating a new static or not

如果这发生在销毁静态对象的过程中,并且会导致重新创建一些已经销毁的静态对象,那么什么时候它们会被销毁?如果它导致循环怎么办?系统应该如何跟踪所有这些?可能的好处是否值得为此付出努力?

可能不会,因为语言标准明确决定不定义它。

关于c++ - 局部静态对象的静态破坏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10353501/

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