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
Playlistowns only astd::vectorofstd::string, and both already know how to copy, move, and destroy.addtakes its argument by value andstd::moves it into the vector, one string copy at most.sizeandfirstareconstaccessors; theprivatesection keeps the storage out of reach.
Keywords and builtins used here
Playlistclassconstprivatepublicreturnsize_tvoid
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.
Step 1 of 3 in Classes & RAII, step 16 of 27 in Language basics.