More C++ Classes: Copy and Move Semantics: Listing 2

Transferring ownership with move semantics.

// move constructor
tree::tree(tree<T>&& other) : root_{ move(other.root_) } {}

// move assignment
tree::tree& operator=(tree<T>&& other)
  // if the left-side tree isn't empty, it's cleared. Existing nodes are deleted.
  if (!is_empty())
  // if the other tree isn't empty, its root is moved.
  if (!other.is_empty()) { root_ = move(other.root_); }

  return *this;

About the Author

Diego Dagum is a software architect and developer with more than 20 years of experience. He can be reached at