gpt4 book ai didi

c++ - const 成员上的 std::construct_at 安全吗?

转载 作者:行者123 更新时间:2023-12-02 01:33:58 25 4
gpt4 key购买 nike

我有课Obj带有 const 成员 i :

class Obj {
const int i;
...
};

但我需要在移动构造函数中将 i 设置为 0。 (因为如果 i 不是 0 ,析构函数将删除内容,并且由于我移动了对象,这将导致双重释放)

修改Obj::i是否安全在这样的移动构造函数中?

Obj::Obj(Obj &&other) :
i(other.i)
{
std::destroy_at(&other.i);
std::construct_at(&other.i, 0);
}

根据我的理解,在 std::construct_at 时执行此操作是安全的将 other.i 替换为“透明可替换对象”。但我不完全确定这个定义的含义:

(8) An object o1 is transparently replaceable by an object o2 if:

(8.1) the storage that o2 occupies exactly overlays the storage that o1 occupied, and
(8.2) o1 and o2 are of the same type (ignoring the top-level cv-qualifiers), and
(8.3) o1 is not a complete const object, and
(8.4) neither o1 nor o2 is a potentially-overlapping subobject ([intro.object]), and
(8.5) either o1 and o2 are both complete objects, or o1 and o2 are direct subobjects of objects p1 and p2, respectively, and p1 is transparently replaceable by p2.

( https://eel.is/c++draft/basic#life-8 )

据我了解,至少8.1、8.2和8.3适用,但我不完全确定,而且我不太理解8.4和8.5。

那么我认为这应该有效(在 C++20 中)是否正确,或者这会导致未定义的行为?

最佳答案

潜在重叠子对象是基类子对象或用 [[no_unique_address]] 标记的成员。 Obj::i 不适用,因此 8.4 适用。

如果您将 p1 和 p2 视为同一个对象,other,则 8.5 可能适用(对象可以透明地替换自身),但它不递归应用(例如,Obj 是某个其他类的基类/[[no_unique_address]] 成员,或者它所属的完整对象是 constother 已是 const_cast 或者是可变成员)。但它实际上总是适用的。

但请考虑不要将其设为 const 成员,因为您确实需要在此处修改它。您的移动构造函数还应该清除 other (例如,将任何指针设置为 nullptr、清除任何文件句柄、将其他内容归零),因此析构函数没有机会不小心双重删除了东西。

关于c++ - const 成员上的 std::construct_at 安全吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72851116/

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