Skip to content

Let Value Members Own Resources

The Course
•
40 min study

Every std::string and std::vector in the tracker holds memory on the heap. Somebody must give that memory back exactly once: not zero times (a leak), not twice (a crash, or worse, silent corruption). In C that somebody is the programmer, with a free call on every path out of every function. In C++ the answer is built into the types: an object that owns a resource releases it in its destructor, and the language runs the destructor automatically when the object's lifetime ends. This idea is called RAII, "resource acquisition is initialization": acquire in the constructor, release in the destructor, and let scope do the rest.

The consequence for your own classes is pleasant. A class whose members are strings, vectors and maps already has correct copying, moving and cleanup, because the compiler generates them member by member and each member knows its own job. Writing none of them yourself is the rule of zero, and it is the default for the whole project.

Predict and run

Bundle holds a vector of strings and declares no special functions. After the copy is changed, what do the two objects hold?

Predict before running C++
#include <iostream>
#include <string>
#include <vector>

struct Bundle { std::vector<std::string> titles; };

int main() {
    Bundle original{{"Read","Review"}};
    Bundle copy = original;
    copy.titles[0] = "Changed";
    std::cout << original.titles[0] << " " << copy.titles[0] << "\n";
    return 0;
}
Check your prediction
Text
Read Changed

The generated copy constructor copied the vector, and the vector copied each string, so copy owns entirely separate memory. Changing it cannot reach original. At the end of main, both destructors run and each frees only its own buffers.

Destructors run at the end of scope

A local object is destroyed when control leaves the block it was declared in, whether by reaching the closing brace or by an early return. Objects in the same scope are destroyed in reverse order of construction, so something built later, which may depend on something earlier, goes first.

Watch lifetimes end C++
#include <iostream>
#include <string>

class Noisy {
public:
    explicit Noisy(std::string name) : name_(std::move(name)) { std::cout << "open " << name_ << "\n"; }
    ~Noisy() { std::cout << "close " << name_ << "\n"; }
    Noisy(const Noisy&) = delete;
    Noisy& operator=(const Noisy&) = delete;
private:
    std::string name_;
};

int main() {
    Noisy a("A");
    {
        Noisy b("B");
        Noisy c("C");
    }
    std::cout << "after block\n";
    return 0;
}
Text
open A
open B
open C
close C
close B
after block
close A

B and C close at the inner brace, newest first, and A closes after the last line of main. The two = delete lines are explained below; they stop this class from being copied.

What goes wrong with a raw owner

Here is a class that manages memory by hand. It looks complete: it allocates in the constructor and frees in the destructor.

C++
class Buffer {
public:
    explicit Buffer(int size) : data_(new int[size]) {}
    ~Buffer() { delete[] data_; }
private:
    int* data_;
};

Buffer first(10);
Buffer second = first; // Generated copy copies the pointer, not the array.
// At scope end both destructors delete the same array: undefined behavior.

The generated copy constructor copies members one by one, and the member is a pointer, so both objects now point at one array. The second delete[] frees memory that is already freed. That is undefined behavior: it may crash, or it may corrupt the allocator and crash much later somewhere unrelated. Assignment has the same problem and also leaks the target's old array.

This is why the rule of three says: if a class needs a user-written destructor, it almost certainly needs a user-written copy constructor and copy assignment too. C++11 added move construction and move assignment, making it the rule of five. Every one of those functions is a place for a bug. The rule of zero avoids all five: hold a std::vector<int> instead of an int*, and the generated versions are correct:

The same class, rule of zero C++
#include <iostream>
#include <vector>

class Buffer {
public:
    explicit Buffer(std::size_t size) : data_(size, 0) {}
    void set(std::size_t index, int value) { data_[index] = value; }
    int get(std::size_t index) const { return data_[index]; }
private:
    std::vector<int> data_;
};

int main() {
    Buffer first(3);
    first.set(0, 7);
    Buffer second = first;
    second.set(0, 9);
    first = second;
    first.set(1, 4);
    std::cout << first.get(0) << " " << first.get(1) << " | " << second.get(0) << " " << second.get(1) << "\n";
    return 0;
}
Text
9 4 | 9 0

The copy, the assignment and both destructors are generated, and each one delegates to std::vector, which copies its elements and frees its own memory exactly once. There is no destructor to forget and no pointer to share.

When you do write a destructor

Sometimes a class exists only to do something at the end of a scope, such as restoring a setting. Then you write the destructor, and the rule of three tells you to decide about copying. Usually the right decision is to forbid it with = delete, as Noisy did, so a copy cannot run the cleanup twice. The practice below builds such a class.

Practice

Exercise

Your turn

Write class Indent that takes an int& depth in its constructor, increments it, and decrements it in its destructor. Delete its copy constructor and copy assignment. Write void log(const std::string& text, int depth) that prints two spaces per level before the text. In main, nest two Indent scopes and print:

Text
start
  inside
    deeper
  back
end

After the program, depth must be 0 again; assert it.

Your workspace C++
#include <cassert>
#include <iostream>
#include <string>

// Write Indent and log here.

int main() {
    int depth = 0;
    return 0;
}
Hint 1: the idea

The constructor does the first half of the job and the destructor the second half. Because the destructor runs at the closing brace whatever happens inside, the depth is always restored.

Hint 2: a first step

Store the reference in a member: int& depth_;, initialized in the member initializer list as depth_(depth). Then the constructor body is ++depth_; and the destructor body is --depth_;. Print the indentation with std::string(2 * depth, ' ').

Show one solution
Run the solution C++
#include <cassert>
#include <iostream>
#include <string>

class Indent {
public:
    explicit Indent(int& depth) : depth_(depth) { ++depth_; }
    ~Indent() { --depth_; }
    Indent(const Indent&) = delete;
    Indent& operator=(const Indent&) = delete;
private:
    int& depth_;
};

void log(const std::string& text, int depth) {
    std::cout << std::string(2 * depth, ' ') << text << "\n";
}

int main() {
    int depth = 0;
    log("start", depth);
    {
        Indent outer(depth);
        log("inside", depth);
        {
            Indent inner(depth);
            log("deeper", depth);
        }
        log("back", depth);
    }
    log("end", depth);
    assert(depth == 0);
    return 0;
}
Text
start
  inside
    deeper
  back
end

Each closing brace runs one destructor, so the depth goes back exactly one level, and the assertion confirms the balance. Without = delete, Indent copy = outer; would compile, because copying a reference member is allowed, and its destructor would decrement a second time. The tracker itself needs none of this: its classes hold strings and maps and follow the rule of zero. The next lesson looks at the other generated operation, moving, and what it leaves behind.

Was this article helpful?

Your response is saved on this device.