Search code examples
c++move

Exception safe move operator


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 !


Solution

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