typestar

The rule of zero in C++

When every member cleans up after itself, the class declares no destructor, no copy, no move: zero special members.

#include <string>
#include <vector>

// Members that manage themselves: no destructor, no copy code to write.
class Playlist {
  public:
    void add(std::string title) { tracks_.push_back(std::move(title)); }
    std::size_t size() const { return tracks_.size(); }
    const std::string& first() const { return tracks_.front(); }

  private:
    std::vector<std::string> tracks_;
};

How it works

  1. Playlist owns only a std::vector of std::string, and both already know how to copy, move, and destroy.
  2. add takes its argument by value and std::moves it into the vector, one string copy at most.
  3. size and first are const accessors; the private section keeps the storage out of reach.

Keywords and builtins used here

The run, in numbers

Lines
13
Characters to type
363
Tokens
88
Three-star pace
75 tpm

At the three-star pace of 75 tokens a minute, this run takes about 70 seconds.

Type this snippet

Step 1 of 3 in Classes & RAII, step 16 of 27 in Language basics.

← Previous Next →