1

While checking &other != this is generally not a good idea in move/copy assignment and the copy-and-swap idiom should be preferred, is it allowed for a swap to perform such a check?

Copy-and-swap idiom:

// same for move, can handle both with `(cls other)`
cls& operator=(const cls& other) {
 cls temp{ other };
 swap(*this, other);
 return *this;
}

std::swap:

template <typename T>
void swap(T& lhs, T& rhs) {
 T tmp{ std::move(lhs); } // move ctor
 lhs = std::move(rhs); // move assign
 rhs = std::move(tmp); // move assign
} // temp dtor

While clearly not helping in assignment which constructs a new temporary, sticking an if (&lhs == &rhs) { return; } at the top of swap could save on operations in some generic code.

Does the standard allow this, or does it say the (2+1) moves are always performed? Are there some reasons why it would not work?

asked Aug 6, 2025 at 7:25
13
  • In generic/library code, prefer std::addressof over unary & which might be evilly overridden. Commented Aug 6, 2025 at 7:29
  • 5
    While you can save some moves, the check itself has cost too. Commented Aug 6, 2025 at 7:33
  • 2
    By 'Idiomatic' do you mean std::swap? Because the 'idiomatic swap' implementation is using std::swap; swap(lhs.member1, rhs.member1); swap(lhs.member2, rhs.member2); ... Commented Aug 6, 2025 at 7:39
  • 2
    It's perhaps worth noting that the "self-check" in assignments is not a matter of performance but of correctness. Commented Aug 6, 2025 at 8:40
  • 1
    Sidenote: An idiomatic move assignment would be cls(std::move(other)).swap(*this); where swap is a member function. Commented Aug 7, 2025 at 1:03

1 Answer 1

10

Language doesn't prevent you from introducing such a check, but self-swap is not expected to be an overly frequent operation, while checking if you swap the same object will require you to pay for itself in every swap, no matter if it's the same object or not.

I.e. the performance gain is questionable, because:

  1. The swap implementation you have given can cover this scenario anyway
  2. If you don't self-swap objects on regular basis, you'll most likely waste more resources on the self-checking, than you'd otherwise waste on a few (redundant) move operations
answered Aug 6, 2025 at 7:38
Sign up to request clarification or add additional context in comments.

1 Comment

Failing branch prediction can be much more costly then making obsolete copy of some data.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.