Of course! Here is a complete C++ class that demonstrates the Rule of Five, along with detailed explanations and a main function to show how each special member function is invoked.
The Rule of Five is a modern C++ guideline that states if you need to explicitly declare any of the following five special member functions, you likely need to declare all five:
- Destructor
- Copy Constructor
- Copy Assignment Operator
- Move Constructor
- Move Assignment Operator
This rule is necessary for classes that manually manage a resource, such as raw memory, a file handle, or a network socket. Our example class, MyString, will manage a dynamically allocated C-style string.
1. The Class Definition (MyString.h)
This header file defines the interface of our class. We clearly label each of the five special members.
// MyString.h
#ifndef MYSTRING_H
#define MYSTRING_H
#include <cstddef> // For size_t
#include <iostream> // For logging
class MyString {
public:
// 1. Default Constructor
MyString(const char* initial_data = "");
// --- The Rule of Five ---
// 2. Destructor
~MyString();
// 3. Copy Constructor (for deep copies)
MyString(const MyString& other);
// 4. Copy Assignment Operator (for deep copies)
MyString& operator=(const MyString& other);
// 5. Move Constructor (for "stealing" resources)
MyString(MyString&& other) noexcept; // 'noexcept' is important for moves
// 6. Move Assignment Operator (for "stealing" resources)
MyString& operator=(MyString&& other) noexcept; // 'noexcept' is important
// --- Utility Functions ---
void print() const;
size_t get_length() const;
private:
char* m_data; // Raw pointer to the managed resource (dynamic C-string)
size_t m_size; // Length of the string (excluding null terminator)
};
#endif // MYSTRING_H
2. The Implementation (MyString.cpp)
Here we implement the logic for each function. Pay close attention to the comments explaining what each one does.
// MyString.cpp
#include "MyString.h"
#include <cstring> // For strlen, strcpy
#include <utility> // For std::swap
// 1. Constructor
MyString::MyString(const char* initial_data) {
std::cout << "CONSTRUCTOR for '" << (initial_data ? initial_data : "") << "'\n";
m_size = initial_data ? strlen(initial_data) : 0;
m_data = new char[m_size + 1]; // +1 for the null terminator '\0'
if (initial_data) {
strcpy(m_data, initial_data);
} else {
m_data[0] = '\0';
}
}
// 2. Destructor
// Releases the managed resource.
MyString::~MyString() {
std::cout << "DESTRUCTOR for '" << (m_data ? m_data : "moved-from object") << "'\n";
delete[] m_data; // Free the dynamically allocated memory
}
// 3. Copy Constructor
// Creates a new object as a DEEP COPY of an existing one.
MyString::MyString(const MyString& other) {
std::cout << "COPY CONSTRUCTOR from '" << other.m_data << "'\n";
m_size = other.m_size;
m_data = new char[m_size + 1]; // Allocate new memory
strcpy(m_data, other.m_data); // Copy the content
}
// 4. Copy Assignment Operator
// Replaces an existing object's content with a DEEP COPY of another.
MyString& MyString::operator=(const MyString& other) {
std::cout << "COPY ASSIGNMENT from '" << other.m_data << "'\n";
// 1. Self-assignment check
if (this == &other) {
return *this;
}
// 2. Free the old resource
delete[] m_data;
// 3. Allocate new memory and copy the content
m_size = other.m_size;
m_data = new char[m_size + 1];
strcpy(m_data, other.m_data);
// 4. Return a reference to the current object
return *this;
}
// 5. Move Constructor
// Creates a new object by "stealing" the resources from a temporary (rvalue) object.
MyString::MyString(MyString&& other) noexcept
: m_data(other.m_data), m_size(other.m_size) { // 1. "Steal" the data pointer and size
std::cout << "MOVE CONSTRUCTOR from '" << m_data << "'\n";
// 2. Leave the "other" object in a valid but empty state.
// This is crucial to prevent its destructor from double-freeing our memory!
other.m_data = nullptr;
other.m_size = 0;
}
// 6. Move Assignment Operator
// Replaces an existing object's content by "stealing" resources from a temporary (rvalue) object.
MyString& MyString::operator=(MyString&& other) noexcept {
std::cout << "MOVE ASSIGNMENT from '" << other.m_data << "'\n";
// 1. Self-assignment check (less common with moves, but still good practice)
if (this == &other) {
return *this;
}
// 2. Free the old resource of the current object
delete[] m_data;
// 3. "Steal" the data and size from the "other" object
m_data = other.m_data;
m_size = other.m_size;
// 4. Neuter the "other" object
other.m_data = nullptr;
other.m_size = 0;
// 5. Return a reference to the current object
return *this;
}
// --- Utility Functions ---
void MyString::print() const {
if (m_data) {
std::cout << "'" << m_data << "' (size: " << m_size << ")\n";
} else {
std::cout << "[moved-from empty object]\n";
}
}
size_t MyString::get_length() const {
return m_size;
}
3. Demonstration (main.cpp)
This file shows each of the special members in action. The print statements from the class will help you see exactly which function is called and when.
// main.cpp
#include "MyString.h"
#include <vector>
// A helper function that returns a MyString by value, which is an rvalue
MyString createMyString(const char* text) {
return MyString(text);
}
int main() {
std::cout << "--- 1. Basic Construction and Destruction ---\n";
{
MyString s1("Hello"); // CONSTRUCTOR
s1.print();
} // DESTRUCTOR for s1 called at end of scope
std::cout << "\n";
std::cout << "--- 2. Copy Construction ---\n";
MyString s2("World"); // CONSTRUCTOR
MyString s3 = s2; // COPY CONSTRUCTOR (s3 is a deep copy of s2)
s2.print();
s3.print();
std::cout << "\n";
std::cout << "--- 3. Copy Assignment ---\n";
MyString s4("Original"); // CONSTRUCTOR
s4 = s2; // COPY ASSIGNMENT (s4's content is replaced by a copy of s2)
s4.print();
std::cout << "\n";
std::cout << "--- 4. Move Construction ---\n";
// std::move casts s3 to an rvalue, allowing the move constructor to be called.
// The resource (pointer) from s3 is "stolen" by s5.
MyString s5 = std::move(s3); // MOVE CONSTRUCTOR
std::cout << "s5's state after move: ";
s5.print();
std::cout << "s3's state after being moved from: ";
s3.print(); // s3 is now empty and safe to destruct
std::cout << "\n";
std::cout << "--- 5. Move Assignment ---\n";
// createMyString("Temporary") returns a temporary object (an rvalue).
// s4's content is replaced by "stealing" the resource from the temporary.
s4 = createMyString("Temporary"); // MOVE ASSIGNMENT
std::cout << "s4's state after move assignment: ";
s4.print();
std::cout << "\n";
std::cout << "--- 6. In a vector (demonstrates copy and move) ---\n";
std::vector<MyString> vec;
vec.push_back(MyString("One")); // Move construction into vector
vec.push_back(MyString("Two")); // Move construction, might cause reallocation
vec.push_back(MyString("Three")); // Move construction, might cause reallocation
std::cout << "\n";
std::cout << "--- End of main, all remaining objects will be destructed ---\n";
return 0;
}
The Rule of Zero: The Modern Best Practice
While the Rule of Five is essential for understanding manual resource management, modern C++ encourages the Rule of Zero.
The Rule of Zero: Design your classes so they don't manage raw resources directly. Instead, use existing resource-managing classes (like std::string, std::vector, std::unique_ptr, std::shared_ptr). If you do this, you don't need to write any of the five special member functions, as the compiler-generated defaults will correctly copy, move, and destroy the member objects for you.
For example, our MyString class could be simplified to this, completely eliminating the need for the Rule of Five:
#include <string>
class BetterString {
private:
std::string m_data; // std::string already handles its own memory!
public:
BetterString(const std::string& initial_data = "") : m_data(initial_data) {}
// No destructor, copy/move constructors, or copy/move assignment operators needed!
// The compiler will generate them, and they will do the right thing by
// calling the corresponding special members of std::string.
};