Sobes.tech
Junior — Middle

How does std::unique_ptr manage automatic deallocation of allocated memory?

sobes.tech AI

Answer from AI

std::unique_ptr is a smart pointer in C++ that owns an object and automatically releases memory when it goes out of scope. It implements the semantics of sole ownership: when the unique_ptr is destroyed, the managed object’s destructor is called, and memory is freed. This prevents memory leaks without manually calling delete.

Example usage:

#include <memory>

void example() {
    std::unique_ptr<int> ptr = std::make_unique<int>(42);
    // ptr will automatically free memory when it goes out of scope
}