Resource Acquisition Is Initialization

suggest change

Resource Acquisition Is Initialization (RAII) ties a resource's lifetime to an object's lifetime. The object acquires the resource during construction and releases it in its destructor. This works for memory, files, locks, sockets, and other resources that require cleanup, including cleanup during stack unwinding.

For dynamically allocated objects, prefer a standard container or a smart pointer. std::unique_ptr expresses exclusive ownership:

#include <iostream>
#include <memory>

int main()
{
    auto value = std::make_unique<int>(5);
    std::cout << *value << '\n';
} // value releases the int automatically
5

A std::unique_ptr cannot be copied, but it can be moved when ownership must be transferred:

auto first = std::make_unique<int>(5);
auto second = std::move(first);
// first is now empty; second owns the int.

Use std::shared_ptr only when the design truly requires shared ownership. It keeps the resource alive until the last owner is destroyed:

#include <iostream>
#include <memory>

int main()
{
    std::shared_ptr<int> outside;
    {
        auto inside = std::make_shared<int>(5);
        outside = inside;
        std::cout << inside.use_count() << '\n';
    }
    std::cout << *outside << '\n';
}
2
5

RAII does not require dynamic allocation. Types such as std::fstream and std::lock_guard directly own their underlying resources. Prefer such scoped objects over manual new/delete, open/close, or lock/unlock pairs.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents