gpt4 book ai didi

c++ - 销毁并重新生成赋值运算符 : what if I'm careful?

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:43:13 26 4
gpt4 key购买 nike

这是一个糟糕的模式。 copy-and-swap 更好。

foo & operator = ( foo const & other ) {
static_assert ( noexcept( new (this) foo() ), "Exception safety violation" );

this-> ~ foo();
try {
new (this) foo( other );
} catch (...) {
new (this) foo(); // does not throw
throw;
}
return * this;
}

只要foonot polymorphic ,会出什么问题? (但是,假设它一个基类。)

背景:我正在处理本地存储类型删除,替代方案是通过本地存储空间将 swap 实现为两个硬编码分配。源和目标的内存 blob 中的对象属于不同类型,根本无法相互交换。根据此类交换定义的复制/移动构造看似没有任何收获,却要复杂两倍。

最佳答案

该标准在 [basic.life] §3.8/7 中对此类中断的生命周期做出了保证:

If, after the lifetime of an object has ended and before the storage which the object occupied is reused or released, a new object is created at the storage location which the original object occupied, a pointer that pointed to the original object, a reference that referred to the original object, or the name of the original object will automatically refer to the new object and, once the lifetime of the new object has started, can be used to manipulate the new object, if:

— the storage for the new object exactly overlays the storage location which the original object occupied, and

— the new object is of the same type as the original object (ignoring the top-level cv-qualifiers), and

— the type of the original object is not const-qualified, and, if a class type, does not contain any non-static data member whose type is const-qualified or a reference type, and

— the original object was a most derived object (§1.8) of type T and the new object is a most derived object of type T (that is, they are not base class subobjects).

最后一点使我的用例不合格。但是,由于这只是针对一个非多态类,因此最好将析构函数和构造函数分别变成 destroyinit 私有(private)成员函数。

换句话说,当 destroy-and-regenerate 合法时,您也可以使用成员函数而不是 new/delete 来做同样的事情。

这样做的一个“优势”是它不再看起来很聪明,所以没有无知的路人想要复制设计。

关于c++ - 销毁并重新生成赋值运算符 : what if I'm careful?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30462113/

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