Technology

CppCon 2019: RAII and the Rule of Zero

Arthur O’Dwyer

Naive Vector

  • Use copy and swap for assignment. Example of recursive shared_ptr in Naivevector

NaiveVector &operator=(const NaiveVector &op2)
{
     NaiveVectory copy = op2;
     copy.swap(*this);
     return *this;
}

  • RAII and exception safety
    • struct RAIIPtr{} example
    • rule of three
    • We don’t want RAIIPtr to be copyable or assignamle

RAIIPTR(const RAIIPTR &) = delete;
RAIIPtr&operator=(const RAIIPtr &op2) = delete;

  • Defaulted special member functions
    • help your code to be self documenting

Rule of Three

If need a destructor then need copy and assignment operators

Rule of Zero

If your class does not directly manage any resource then strive to write no special member functions

But your own swap might improve performance

Introducing rvalue references

As a general rule, lvalue reference parameters do not bind to rvalues and rvalue reference parameters do not bind to lvalues. A const ref will bind to rvalue

Move constructor

Rule of Five

  • A destructor
  • copy constructor
  • move constructor to transfer ownership (for performance)
  • copy assignment operator
  • move assignment operator (for performance)

Copy-and-swap leads to duplication

NaiveVector& NaiveVector:operator=(NaiveVector &&rhs){
    NaiveVector copy(std::move(rhs));
    copy.swap(*this);
    return *this
}

By-value assignment operator

NaiveVector &operator=(NaiveVector copy)
{
   copy.swap(*this);
   return *this;
}

Rule of Four (and a half)

  • destructor
  • copy constructor
  • move constructor
  • by-value assignment operator
  • 1/2 (A nonmember swap() function, and idealy a member version too)

No longer

Cluster to rule of zero

  • Use std::unique_ptr() and we can default the move constructor
  • Other constructors are fine (including Allocator)

Examples of resource management

  • unique_ptr
  • shared_ptr
  • unique_lock
  • ifstream

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.