Site Tools


wiki:cpp-rule-of-five

Table of Contents

C++ Rule of five

Rule of five states that if a class defines any of the destructor, copy constructor, copy assignment, move constructor, or move assignment, it should define all five to ensure correct resource management. Without explicit definitions, the compiler generates defaults that may not handle custom resources correctly.

Prefer the C++ Rule of zero by using standard library types that manage resources for you.

Example

This example shows how omitting move semantics causes unnecessary copies and why all five should be defined together.

// compile: g++ -o rof rof.cpp
// run: ./rof
// description: demonstrate why all five special members need explicit definition
 
#include <iostream>
#include <cstring>
 
class MyBuffer {
    char* data;
    size_t size;
public:
    MyBuffer(const char* str) : size(strlen(str)) {
        data = new char[size + 1];
        strcpy(data, str);
    }
 
    ~MyBuffer() { delete[] data; }
 
    MyBuffer(const MyBuffer& other) : size(other.size) {
        data = new char[size + 1];
        strcpy(data, other.data);
    }
 
    MyBuffer& operator=(const MyBuffer& other) {
        if (this != &other) {
            delete[] data;
            size = other.size;
            data = new char[size + 1];
            strcpy(data, other.data);
        }
        return *this;
    }
 
    MyBuffer(MyBuffer&& other) noexcept : data(other.data), size(other.size) {
        other.data = nullptr;
    }
 
    MyBuffer& operator=(MyBuffer&& other) noexcept {
        delete[] data;
        data = other.data;
        size = other.size;
        other.data = nullptr;
        return *this;
    }
};
 
int main() {
    MyBuffer a("hello");
    MyBuffer b = std::move(a);  // uses move constructor
    return 0;
}
wiki/cpp-rule-of-five.md · Last modified: by 127.0.0.1