Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Rewrite assignment operators using newer idioms #28

Open
htiek opened this issue Jun 22, 2018 · 0 comments
Open

Rewrite assignment operators using newer idioms #28

htiek opened this issue Jun 22, 2018 · 0 comments

Comments

@htiek
Copy link
Collaborator

htiek commented Jun 22, 2018

Our current assignment operator implementations use this general idiom:

 Object& operator =(const Object& rhs) {
     if (this != &other) {
         clear();
         deepCopy(other);
     }
     return *this;
  }

This has a few drawbacks:

  1. It's not exception-safe. If something bad happens during the copy step, the internal state is corrupted.
  2. It requires the logic for performing a deep copy to be factored out of the copy constructor.
  3. It doesn't play well with move semantics.

The more modern C++ approach is to write an assignment operator like this:

Object& operator =(Object rhs) {
    swap(*this, rhs);
    return *this;
 }

This "construct-and-swap" idiom just requires the definition of a swap function that does a memberwise swap and lets the compiler decide whether to construct the argument using copy semantics or move semantics. There's no need to factor the copy logic out of the constructor.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant