← C++ Index

🧠 <memory> — Smart Pointers — unique_ptr, shared_ptr, weak_ptr

Modern C++ memory management. Smart pointers automatically delete objects when they go out of scope. Prefer smart pointers over raw new/delete.

Include: #include <memory> | Namespace: std | Compile: g++ -Wall -std=c++17 ...

📋 Classes, Functions & Symbols

NameType / SignatureDescription
std::unique_ptr<T>class templateExclusive ownership — destructs when out of scope
std::make_unique<T>(…)unique_ptr<T>Create unique_ptr (preferred, C++14)
up.get()T *Return raw pointer (no ownership transfer)
up.release()T *Release ownership; return raw pointer
up.reset(ptr)voidReplace managed pointer (old one deleted)
*up / up->memberT &Dereference / member access
std::shared_ptr<T>class templateShared ownership — ref-counted
std::make_shared<T>(…)shared_ptr<T>Create shared_ptr efficiently (C++11)
sp.use_count()longNumber of shared_ptrs sharing ownership
std::weak_ptr<T>class templateNon-owning observer (breaks cycles)
wp.lock()shared_ptr<T>Obtain shared_ptr if object still alive
wp.expired()boolTrue if the managed object was destroyed

💡 Example Program

Copy, save as demo.cpp, and compile with the command at the bottom.

#include <iostream>
#include <memory>
#include <string>
using namespace std;

struct Animal {
    string name;
    Animal(const string &n) : name(n) {
        cout << "  ['" << name << "' created]\n";
    }
    ~Animal() { cout << "  ['" << name << "' destroyed]\n"; }
    void speak() const { cout << name << " says hello!\n"; }
};

void demo_unique() {
    cout << "=== unique_ptr ===\n";
    auto dog = make_unique<Animal>("Rex");
    dog->speak();
}  // automatically deleted here

void demo_shared() {
    cout << "=== shared_ptr ===\n";
    shared_ptr<Animal> a = make_shared<Animal>("Cat");
    cout << "  use_count=" << a.use_count() << "\n";
    {
        shared_ptr<Animal> b = a;
        cout << "  use_count=" << a.use_count() << "\n";
        b->speak();
    }
    cout << "  use_count=" << a.use_count() << "\n";
}

int main() {
    demo_unique();
    demo_shared();
    cout << "Done.\n";
    return 0;
}
// Compile: g++ -Wall -std=c++17 -o memory_demo memory_demo.cpp

← <sstream>  |  🏠 Index  |  <stdexcept> →