Constructor Suppression Rules
When a special member function is declared (including = default and = delete), it can suppress the implicit generation of the other special member functions. ✓ means the special member function was compiler-generated, and × means it was not or deleted:
| Declared | Default constructor | Destructor | Copy constructor | Copy assignment | Move constructor | Move assignment |
|---|---|---|---|---|---|---|
| Nothing | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ |
| Any constructor | × | ✓ | ✓ | ✓ | ✓ | ✓ |
| Default constructor | - | ✓ | ✓ | ✓ | ✓ | ✓ |
| Destructor | ✓ | - | ✓ | ✓ | × | × |
| Copy constructor | × | ✓ | - | ✓ | × | × |
| Copy assignment | ✓ | ✓ | ✓ | - | × | × |
| Move constructor | × | ✓ | × | × | - | × |
| Move assignment | ✓ | ✓ | × | × | × | - |
Rule of Three
If a class defines any of the destructor, copy constructor, or copy assignment - it almost certainly needs all three.
A class that needs a destructor usually owns a resource, so it also needs a copy constructor and copy assignment to deep copy the resource:
class Buffer {
public:
Buffer(int n) : size(n), data(new int[n]) {}
Buffer(const Buffer& other) : size(other.size), data(new int[other.size]) {
std::copy#include <algorithm>(other.data, other.data + size, data);
}
Buffer& operator=(const Buffer& other) {
if (this != &other) {
delete[] data;
size = other.size;
data = new int[size];
std::copy#include <algorithm>(other.data, other.data + size, data);
}
return *this;
}
~Buffer() { delete[] data; }
int size;
int* data;
};Rule of Five
If a class defines any of the destructor, copy constructor, copy assignment, move constructor, or move assignment - it almost certainly needs all five.
A class that needs deep copying usually wants move semantics:
class Buffer {
public:
// Constructor, destructor and copy operations as above.
Buffer(Buffer&& other) noexcept : size(other.size), data(other.data) {
other.size = 0;
other.data = nullptr;
}
Buffer& operator=(Buffer&& other) noexcept {
if (this != &other) {
delete[] data;
size = other.size;
data = other.data;
other.size = 0;
other.data = nullptr;
}
return *this;
}
int size;
int* data;
};
Buffer a(10);
Buffer b = std::move#include <utility>(a); // Takes a's array.Rule of Zero
Define none of the five where possible.
A class whose members manage their own resources will already copy and move correctly:
class Buffer {
public:
Buffer(int n) : data(n) {}
std::vector#include <vector><int> data;
};
Buffer a(10);
Buffer b = a; // Copies the vector.
Buffer c = std::move#include <utility>(a); // Moves the vector.
Dan