Skip to content

Latest commit

 

History

History
43 lines (36 loc) · 1.12 KB

copy_swap.md

File metadata and controls

43 lines (36 loc) · 1.12 KB

The Copy & Swap Idiom

The copy & swap idiom allows you to implement assignment operators and even the move constructor using a swap operation.

Copy Assignment

?inline

T& T::operator=(
    T other)
{
    using std::swap;
    swap(*this, other);
    return *this;
}

Move Assignment (Optional)

?inline

T& T::operator=(
    T&& other)
{
    using std::swap;
    swap(*this, other);
    return *this;
}

Explanation

Because of argument-dependent lookup (ADL), our own swap(T&, T&) function may be called instead of std::swap.

✅ simple implementation of assignments (and move constructor)
✅ well-defined self-assignment
noexept copy/move assignment if std::is_nothrow_swappable
❌ copying always takes place, even for self-assignment

See Also

<:stackoverflow:874353689031233606> What is the copy-and-swap idiom? (must read!)