简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM