Skip to content
KALANBLON
Show contents

Chapter 5 of 7 · 20 min

Memory without leaks: RAII and unique_ptr

By the end of this chapter, you'll be able to

  • Explain an object's lifetime and the role of the destructor
  • State the RAII principle
  • Use std::unique_ptr and std::make_unique instead of new and delete
  • Recognise a memory leak caused by new without delete

Lifetime and destructor

An object declared in a block { … } is destroyed automatically when the block ends. Just before that, C++ calls its destructor, a method named ~ClassName. Objects are destroyed in the reverse order of their creation.

#include <iostream>
#include <string>

class Logbook {
public:
    explicit Logbook(const std::string& name) : name_(name) {
        std::cout << "Opening " << name_ << "\n";
    }
    ~Logbook() {
        std::cout << "Closing " << name_ << "\n";
    }
private:
    std::string name_;
};

int main() {
    std::cout << "Start\n";
    {
        Logbook a("A");
        Logbook b("B");
        std::cout << "Working\n";
    }                                   // end of block: b then a are destroyed
    std::cout << "End\n";
    return 0;
}
Start
Opening A
Opening B
Working
Closing B
Closing A
End

The explicit keyword stops the compiler from silently converting a text into a Logbook. It's a good habit for constructors with a single parameter.

The RAII principle

RAII stands for "Resource Acquisition Is Initialization". In practice:

  1. the constructor acquires the resource (memory, a file, a network connection…);
  2. the destructor releases it;
  3. since the destructor is called automatically, even in case of an error or an early return, the resource is always released.

You already use it without knowing: std::string and std::vector allocate memory in their constructor and give it back in their destructor. You've never had to call free.

By contrast, with a manual new, one forgotten return and the memory is never given back.

Step 5 of 5
Text description of the animation
  1. make_unique allocates the object and hands it to p, its only owner.
  2. We use it like a pointer, with -> and *.
  3. However the block is left, p is destroyed.
  4. Its destructor frees the object: no leak possible, without writing delete.
  5. By contrast, with a manual new, one forgotten return and the memory is never given back.

std::unique_ptr: a single owner

When you really need to allocate an object dynamically (its size or type is only known at run time, or it must outlive the block that created it), use std::unique_ptr, from <memory>. It's a pointer that owns the object and destroys it automatically.

#include <iostream>
#include <memory>

struct Image {
    int width;
    int height;
};

int main() {
    std::unique_ptr<Image> img = std::make_unique<Image>(Image{1920, 1080});
    std::cout << img->width << " x " << img->height << "\n";

    std::unique_ptr<Image> other = std::move(img);   // transfer of ownership
    std::cout << std::boolalpha << (img == nullptr) << " " << other->width << "\n";
    return 0;
}                                                    // the image is freed here
1920 x 1080
true 1920
  • std::make_unique<Image>(…) creates the object and returns its unique_ptr.
  • You use it like a pointer: img->width, *img.
  • A unique_ptr can't be copied (there's only one owner), but it can be moved with std::move: ownership passes to other, and img becomes empty (nullptr).

For several owners of the same object, there's std::shared_ptr, which costs more. In the vast majority of cases, a std::vector, an ordinary object or a unique_ptr is enough.

Your turn

Worked exercise

Worked exercise: getting rid of new and delete

Rewrite read_sensor without new or delete, so that no leak is possible, whatever path is taken. The program must display -1 then 21.

Hint 1
A dynamically allocated array of 1000 integers is exactly the job of std::vector<int> readings(1000);.
Hint 2
The vector is destroyed automatically at every return: you can remove the delete[].
Show the solution and common mistakes
#include <iostream>
#include <vector>

int read_sensor(bool broken) {
    std::vector<int> readings(1000);      // 1000 integers at 0, freed automatically
    if (broken) {
        return -1;                        // no leak possible any more
    }
    readings[0] = 21;
    return readings[0];
}

int main() {
    std::cout << read_sensor(true) << "\n";
    std::cout << read_sensor(false) << "\n";
    return 0;
}
-1
21

Common mistakes:

  • Writing std::vector<int> readings{1000}; with curly braces: that creates a vector with a single item, equal to 1000. With parentheses, you get 1000 items.
  • Keeping a delete "just in case": you never free yourself memory that's managed by an RAII object.

Summary

  1. 1An object is destroyed automatically at the end of its block; its destructor ~Class() is then called.
  2. 2RAII: the constructor acquires a resource, the destructor releases it, always.
  3. 3std::string, std::vector and std::unique_ptr apply RAII to memory.
  4. 4std::make_unique creates an object owned by a unique_ptr; std::move transfers ownership.
  5. 5In modern C++, no new or delete in your code.

Your progress is saved on this device. Create a free account to keep your progress on all your devices.