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 ...
| Name | Type / Signature | Description |
|---|---|---|
| std::unique_ptr<T> | class template | Exclusive 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) | void | Replace managed pointer (old one deleted) |
| *up / up->member | T & | Dereference / member access |
| std::shared_ptr<T> | class template | Shared ownership — ref-counted |
| std::make_shared<T>(…) | shared_ptr<T> | Create shared_ptr efficiently (C++11) |
| sp.use_count() | long | Number of shared_ptrs sharing ownership |
| std::weak_ptr<T> | class template | Non-owning observer (breaks cycles) |
| wp.lock() | shared_ptr<T> | Obtain shared_ptr if object still alive |
| wp.expired() | bool | True if the managed object was destroyed |
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