C++

Lesson 05

Rule of zero

Prefer standard-library members so copy, move, and destruction follow generated behavior instead of manual pointer code.

Good Code

src/review_summary.cpp
#include <string>
#include <utility>
#include <vector>

class ReviewSummary {
public:
    ReviewSummary(std::string title, std::vector<int> scores)
        : title_(std::move(title)), scores_(std::move(scores)) {}

    // Standard members keep copy and move behavior generated by the type.
private:
    std::string title_;
    std::vector<int> scores_;
};

Bad Code

review_summary.cpp
#include <cstring>

class ReviewSummary {
public:
    explicit ReviewSummary(const char* title)
        : title_(new char[std::strlen(title) + 1])
    {
        std::strcpy(title_, title);
    }

    // Manual destructor without copy control makes copies share one pointer.
    ~ReviewSummary()
    {
        delete[] title_;
    }

private:
    char* title_;
};

Review Notes

What to review

Good Code

The good version stores standard-library values, so generated copy, move, and destruction rules are enough.

Bad Code

The bad version owns a raw character buffer and defines only a destructor. The compiler still generates copying, which can make two objects delete the same pointer.

Takeaways

  • If a class does not own raw resources directly, it usually should not define a destructor, copy constructor, or move constructor.