[英]can I call destructor in move assignment operator?
Is calling a d-tor inside move assignment operator good practice? 在移动分配操作员里面调用一个d-tor好习惯吗?
here some example code: 这里有一些示例代码:
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;
}
Should I use this code, or should I use swap() with move constructed object? 我应该使用此代码,还是应该使用swap()与移动构造对象?
~VectorList
does more than run the code in the dtor body: it actually destroys the object. ~VectorList
不仅运行dtor体中的代码:它实际上会破坏对象。
After that, the storage is unused. 之后,存储空间未使用。 You can construct a new object there using a constructor, but simply accessing members is going to either be undefined behaviour, or require language-lawyers to find the loophole that lets it be defined.
您可以使用构造函数在那里构造一个新对象,但只是访问成员将是未定义的行为,或者需要语言律师找到允许它被定义的漏洞。
Even if defined, it is dangerous, as an exception thrown while an automatic storage object is destroyed is bad news. 即使被定义,它也是危险的,因为在销毁自动存储对象时抛出的异常是坏消息。 Plus if the assigned-to class is actually of derived type, the dtor call itself is UB!
另外,如果指定的类实际上是派生类型,则dtor调用本身就是UB!
Neither is a worthwhile approach. 这两种方法都不值得。 The benefits are too small.
好处太小了。
The better alternative is copy-swap (which is at least easy to get correct: it can prevent some optimizations), or refactor out the 'clear' code from both the dtor and assignment. 更好的选择是copy-swap(至少很容易纠正:它可以阻止一些优化),或者从dtor和赋值中重构出“clear”代码。 Then call it at both spots.
然后在两个地方打电话给它。
Scott Meyers says don't use swap()
: http://scottmeyers.blogspot.sg/2014/06/the-drawbacks-of-implementing-move.html Scott Meyers说不要使用
swap()
: http : //scottmeyers.blogspot.sg/2014/06/the-drawbacks-of-implementing-move.html
Regarding your current implementation, it seems you can do it more simply. 关于您当前的实施,似乎您可以更简单地做到这一点。 I imagine that the destructor actually deletes
_buffer
and does little else. 我想析构函数实际上删除了
_buffer
并且没有其他功能。 If that's true, you should just replace your harder-to-reason-about explicit destructor call with delete _buffer
. 如果这是真的,你应该用
delete _buffer
替换你更难delete _buffer
显式析构函数调用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.