【发布时间】:2015-09-26 11:34:04
【问题描述】:
在移动赋值运算符中调用 d-tor 是一种好习惯吗?
这里有一些示例代码:
VectorList &operator = (VectorList &&other){
~VectorList(); // if this is not a good practice,
// I will need to paste whole d-tor here.
_buffer = std::move(other._buffer );
_dataCount = std::move(other._dataCount );
_dataSize = std::move(other._dataSize );
other._clear();
return *this;
}
我应该使用这段代码,还是应该使用带有移动构造对象的 swap()?
【问题讨论】:
-
您是否考虑过创建一个函数来“清理”对象并从析构函数和移动赋值运算符中调用该函数?
-
析构函数通常不负责将对象返回到初始化状态,所以这样做我会感到不舒服。为什么不打电话给
this->clear()? -
@Nick 作为旁注,我希望你知道
std::move不会“移动”任何东西,它只是对右值引用的强制转换。如果_buffer是一个原始指针,那么_buffer = other._buffer;就足够了。 -
是的,但斯科特迈耶斯“告诉”我你应该用移动来做,因为更好的风格和表现出意图。 std::move 是一个简单的演员表...
标签: c++ c++11 dry move-assignment-operator