← Zurück zum Kurs: Modern C++ from scratch

RAII and destructors: resources that clean up by themselves

Video folgt in Kürze

A real program acquires resources: dynamic memory, open files, network connections, locks. They all have something in common: they must be released exactly once, even if the function ends early through an early return or an exception. In languages with garbage collection or try-finally this is solved by hand; C++ offers something better and more elegant: the RAII idiom, short for Resource Acquisition Is Initialization. The idea is simple: the resource is acquired in an object's constructor and released in its destructor, and since the destructor runs automatically when leaving the scope, the cleanup is never forgotten.

The destructor

The destructor is written with the class name preceded by a tilde, ~Name(), with no parameters or return. It is invoked when the object's life ends: on reaching the end of the block where it was declared, or when the object containing it is destroyed. Local objects are destroyed in reverse order of creation, like a stack of plates. This makes cleanup predictable. The following program uses a class that only prints messages so you can see the exact order of construction and destruction, even when the flow leaves the block through an early return.

cpp
#include <iostream>
#include <string>
#include <utility>

class Tracer {
public:
    explicit Tracer(std::string name) : name_{std::move(name)} {
        std::cout << "create " << name_ << '\n';
    }
    ~Tracer() {
        std::cout << "destroy " << name_ << '\n';
    }

private:
    std::string name_;
};

int work(bool early) {
    Tracer first{"first"};
    Tracer second{"second"};
    if (early) {
        return 1;   // both objects are still destroyed
    }
    Tracer third{"third"};
    return 0;
}

int main() {
    work(true);
    // create first
    // create second
    // destroy second
    // destroy first
    return 0;
}

A real resource: dynamic memory

Let us see RAII with memory. The IntBuffer class reserves an array with new[] in the constructor and frees it with delete[] in the destructor. The user never writes new or delete: they create an object and forget about it. There is an important trap: if the class manages a resource, the default copy would copy only the pointer, and two objects would try to free the same memory (double free, undefined behavior). That is why we apply the rule of five in a simple version: if you define a destructor, decide what happens on copy and move. The safest way to start is to forbid copying with = delete.

cpp
#include <cstddef>
#include <iostream>

class IntBuffer {
public:
    explicit IntBuffer(std::size_t size)
        : size_{size}, data_{new int[size]{}} {   // {} zero-initializes
        std::cout << "buffer of " << size_ << " ints acquired\n";
    }

    ~IntBuffer() {
        delete[] data_;
        std::cout << "buffer released\n";
    }

    // copying would duplicate the pointer and cause a double delete
    IntBuffer(const IntBuffer&) = delete;
    IntBuffer& operator=(const IntBuffer&) = delete;

    int& at(std::size_t i) { return data_[i]; }   // no bounds check, kept simple
    std::size_t size() const { return size_; }

private:
    std::size_t size_;
    int* data_;
};

int main() {
    IntBuffer buf{4};
    buf.at(0) = 10;
    buf.at(3) = 40;
    std::cout << buf.at(0) + buf.at(3) << '\n';   // 50
    // buffer of 4 ints acquired
    // 50
    // buffer released   (printed automatically at the end of main)
    return 0;
}

In practice, in modern C++ you rarely write new and delete yourself: the library already ships ready RAII classes. std::vector manages its memory, std::string too, std::unique_ptr (which you will see in week 7) manages dynamic objects, std::ifstream closes the file when destroyed and std::lock_guard releases the lock. This practice is summed up in the rule of zero: if your class only uses members that already manage their resources, you do not need to write a destructor or copy; the compiler generates everything correctly. Write your own destructors only when you wrap a new resource, such as a handle from a C library.

✎ Meine Notizen

Nur in diesem Browser gespeichert. Melde dich an, um es im Konto zu behalten.0/5000 Zeichen

← ZurückWeiter →