Is calling a d-tor inside move assignment operator good practice?
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?
~VectorList
does more than run the code in the dtor body: it actually destroys the object.
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!
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. 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
Regarding your current implementation, it seems you can do it more simply. I imagine that the destructor actually deletes _buffer
and does little else. If that's true, you should just replace your harder-to-reason-about explicit destructor call with delete _buffer
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With