gpt4 book ai didi

c++ - 如何避免在const自动对象曾经使用的存储中创建任何对象?

转载 作者:行者123 更新时间:2023-12-01 15:05:02 24 4
gpt4 key购买 nike

C++(草稿)标准包含了我称为[basic.life]/10的“ROMability子句”:

Creating a new object within the storage that a const complete object with static, thread, or automatic storage duration occupies, or within the storage that such a const object used to occupy before its lifetime ended, results in undefined behavior.



第一部分很好:“静态线程”“存储持续时间”。允许此类存储的重用是不合理的。

但是最后一部分呢:

automatic storage duration occupies, or within the storage that such a const object used to occupy before its lifetime ended



这是否意味着 用户需要避免在堆栈可能已使用(存储自动对象的)的任何内存位置中创建任何对象?

这将阻止在自动对象的任何子对象上使用new放置,或使用执行此操作的库工具。

这是零意义,但在我看来,这实际上是在此处指定的内容。

最佳答案

the user needs to be avoid creating any object in any memory location that might have been used by the stack (to store automatic objects)



该标准不了解“堆栈”,也不在乎-这是一个实现细节。

Block-scope variables not explicitly declared static, thread_­local, or extern have automatic storage duration.

The storage for these entities lasts until the block in which they are created exits

from [basic.stc.auto]



因此,即使两个实体最终(没有重叠存储)位于“堆栈”上的相同地址上,它们仍然没有相同的存储。
union Lazy {
Thing thing;
};

// later in a function
{
Thing const first = /* init */
}
{
Lazy l;
new (&l.thing) Thing();
}
firstl.thing可能位于相同的地址上……但是创建 l.thing时, first的存储已“消失”。

“底线”:相同的地址并不意味着相同的存储。

关于c++ - 如何避免在const自动对象曾经使用的存储中创建任何对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59317511/

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