Table of Contents

<memory>

<memory> provides smart pointers—std::unique_ptr<T> (exclusive ownership), std::shared_ptr<T> (reference-counted ownership)—and std::make_unique, std::make_shared factories. Smart pointers automatically delete memory via RAII, preventing leaks and use-after-free.

Use std::unique_ptr by default; use std::shared_ptr only when you need shared ownership semantics. Avoid raw new/delete in modern C++.

Example

This example demonstrates exclusive ownership with uniqueptr and reference-counted ownership with sharedptr, showing automatic cleanup.

// compile: g++ -std=c++11 -o memoryexample memoryexample.cpp
// run: ./memoryexample
// description: smart pointers and automatic cleanup
 
#include <memory>
#include <iostream>
 
int main() {
    {
        auto ptr = std::make_unique<int>(42);
        std::cout << "unique_ptr value: " << *ptr << "\n";
    }
 
    auto sptr = std::make_shared<int>(99);
    {
        auto sptr2 = sptr;
        std::cout << "use_count: " << sptr.use_count() << "\n";
    }
    std::cout << "use_count after scope: " << sptr.use_count() << "\n";
 
    return 0;
}