skip to content
Ivan's wiki
Site Tools
Search
Tools
Show pagesource
Backlinks
Recent Changes
Media Manager
Sitemap
>
Recent Changes
Media Manager
Sitemap
cpp-rule-of-five
This page is read only. You can view the source, but not change it.
# C++ rule of five **[Rule of five](https://en.cppreference.com/w/cpp/language/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](/cpp-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. ```cpp // 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; } ```
Page Tools
Show pagesource
Backlinks
Back to top