Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

can I call destructor in move assignment operator?

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?

like image 234
Nick Avatar asked Mar 15 '23 16:03

Nick


2 Answers

~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.

like image 88
Yakk - Adam Nevraumont Avatar answered Mar 25 '23 10:03

Yakk - Adam Nevraumont


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.

like image 23
John Zwinck Avatar answered Mar 25 '23 09:03

John Zwinck