Default functions
Use case
Explicitly request compiler-generated special member functions (constructors, assignment operators and destructors). We implement a custom destructor for logging.
Explanation
The destructor is only for logging but defining it suppresses move generation. = default request all operations back. Since std::vector handles deep copy and move correctly, default operations are fine. According to the rule of 5, we implement all.
Code
#include <iostream>
#include <string>
#include <vector>
class DisassemblyResult {
std::vector<std::string> instructions;
public:
DisassemblyResult() = default;
~DisassemblyResult() {
std::cout << "Cleanup: " << instructions.size() << " instructions.\n";
}
// Copy constructor.
DisassemblyResult(const DisassemblyResult &) = default;
// Copy assignment.
DisassemblyResult &operator=(const DisassemblyResult &) = default;
// Move constructor.
DisassemblyResult(DisassemblyResult &&) = default;
// Move assignment.
DisassemblyResult &operator=(DisassemblyResult &&) = default;
void add(const std::string &s) { instructions.push_back(s); }
size_t count() const { return instructions.size(); }
};
int main() {
DisassemblyResult a;
a.add("stp x29, x30, [sp, #-16]!");
a.add("mov x29, sp");
DisassemblyResult b = a;
DisassemblyResult c = std::move(a);
std::cout << "a: " << a.count() << ", b: " << b.count() << ", c:" << c.count()
<< "\n";
return 0;
}
Output
$ ./src/c++11/build/default-functions
a: 0, b: 2, c:2
Cleanup: 2 instructions.
Cleanup: 2 instructions.
Cleanup: 0 instructions.