Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exception safe move operator

Tags:

c++

move

I generally (try to) write exception safe copy assignment operators using the copy-swap idiom, and I was wondering if I should be concerned about exceptions when writing the move assignement operators. Here is an example of a copy assignement operator:

template<class T>
CLArray<T>&
CLArray<T>::operator=( const CLArray& rhs )
{
    CLArray tmp( rhs );
    std::swap( size_, tmp.size_ );
    std::swap( data_, tmp.data_ );
    return *this;
}

But what about the move assignement ? I mean, if an exception is thrown somewhere else in the code during THIS move operation, I will lose the state of both objects right ? So I would have to create a local copy first and then delete everything but the newly created CLArray ...

template <class T>
CLArray<T>&
CLArray<T>::operator=( CLArray<T>&& rhs )
{
    size_ = rhs.size_;
    data_ = std::move( rhs.data_ );
    return *this;
}

Please note that data_ is a std::vector, and thanks for the answers !

like image 618
Athanase Avatar asked Feb 02 '26 09:02

Athanase


1 Answers

Indeed, it can be difficult or impossible to provide exception guarantees if a move constructor might throw.

I would suggest doing as the standard library does: document that certain operations only have exception guarantees (or, in some cases, are only permitted) if move-construction of T doesn't throw. Ensuring the guarantee by copying the object destroys the benefit of move-assignment for all types, not just the (very rare) ones that might throw.

like image 177
Mike Seymour Avatar answered Feb 04 '26 23:02

Mike Seymour



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!