...

/

Resource Acquisition and the Rule of Five

Resource Acquisition and the Rule of Five

Learn about the concept of the rule of five with implementing functions.

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_:

Press + to interact
// 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 ...