Search⌘ K
AI Features

Resource Acquisition and the Rule of Five

Explore the rule of five in C++ to manage class resources effectively. Understand how to implement copy constructors, copy assignments, destructors, and extend them with move semantics for optimized resource transfers. This lesson helps you handle memory and other resources efficiently while preventing unnecessary copies and ensuring safe class behavior.

Securing resources through the rule of five

To fully understand move semantics, we need to go back to the basics of classes and resource acquisition in C++. One of the basic concepts in C++ is that a class should completely handle its resources. This means that when a class is copied, moved, copy-assigned, move-assigned, or destructed, the class should make sure its resources are handled accordingly. The necessity of implementing these five functions is commonly referred to as the rule of five.

Let's have a look at how the rule of five can be implemented in a class handling an allocated resource. In the Buffer class defined in the following code playground, the allocated resource is an array of floats pointed at by the raw pointer ptr_:

C++ 17
// Rule of five
class Buffer {
public:
// Constructor
Buffer(const std::initializer_list<float>& values)
: size_{values.size()} {
ptr_ = new float[values.size()];
std::copy(values.begin(), values.end(), ptr_);
}
auto begin() const { return ptr_; }
auto end() const { return ptr_ + size_; }
private:
size_t size_{0};
float* ptr_{nullptr};
};

In this case, the handled resource is a block of memory allocated in the constructor of the Buffer ...