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-zero
This page is read only. You can view the source, but not change it.
# C++ rule of zero **[Rule of zero](https://en.cppreference.com/w/cpp/language/rule_of_zero)** states that if a class manages resources correctly via [RAII](/raii), it should define no special member functions at all—not destructor, copy constructor, copy assignment, move constructor, or move assignment. The compiler's defaults work correctly when members are themselves RAII-compliant (e.g., `unique_ptr`, `vector`, `string`). Prefer the rule of zero by using standard library containers and smart pointers instead of manual resource management. ## Example This example shows how using standard library types makes manual special members unnecessary. ```cpp // compile: g++ -o rule_zero rule_zero.cpp // run: ./rule_zero // description: rule of zero: no special members needed with standard containers #include <iostream> #include <vector> #include <memory> class Container { private: std::vector<int> data; std::unique_ptr<int[]> buffer; public: Container(size_t n) : buffer(std::make_unique<int[]>(n)) {} // No destructor, copy constructor, copy assignment, move constructor, or move assignment needed // Compiler-generated versions work correctly due to RAII members }; int main() { Container c1(100); Container c2 = std::move(c1); // move works correctly Container c3 = c2; // copy works correctly return 0; } ```
Page Tools
Show pagesource
Backlinks
Back to top