Modern C++ Smart Pointers: std::unique_ptr and std::shared_ptr
Eliminate manual delete calls and memory leaks using RAII-driven smart pointers introduced in modern C++.
Concepts & Theory
`std::unique_ptr` enforces sole ownership of dynamic resources. It cannot be copied, only moved via `std::move`, and cleans up on scope exit.
`std::shared_ptr` implements thread-safe reference counting. The resource is destroyed when the final owner goes out of scope.
Prefer `std::make_unique<T>()` and `std::make_shared<T>()` factory helpers for exception safety and single-allocation efficiency.
Code Example
Run in Playground#include <iostream>
#include <memory>
#include <string>
class Vaisseau {
public:
std::string nom;
Vaisseau(std::string n) : nom(n) { std::cout << "[+] " << nom << " construit\n"; }
~Vaisseau() { std::cout << "[-] " << nom << " detruit proprement\n"; }
void tirer() { std::cout << nom << " fait feu !\n"; }
};
int main() {
// 1. Propriété exclusive avec unique_ptr (recommandé par défaut)
auto vaisseau1 = std::make_unique<Vaisseau>("Carthage-X1");
vaisseau1->tirer();
// 2. Transfert de propriété avec move semantics
std::unique_ptr<Vaisseau> vaisseau2 = std::move(vaisseau1);
// vaisseau1 est maintenant nullptr, vaisseau2 est propriétaire
// Sortie de scope : la mémoire est désallouée automatiquement sans delete !
return 0;
}Common Pitfalls & Mistakes
✗ Instantiating smart pointers with raw new
std::unique_ptr<Vaisseau> v(new Vaisseau("X1"));auto v = std::make_unique<Vaisseau>("X1");`std::make_unique` is exception-safe and avoids raw pointer leaks if constructor arguments throw.
Frequently Asked Questions
When should I prefer unique_ptr over shared_ptr?▾
Use `std::unique_ptr` by default: it has zero runtime overhead compared to raw pointers. Use `shared_ptr` only when multiple entities genuinely share ownership.
Master C++ with interactive exercises
Complete hands-on code challenges in your browser with real-time feedback and progressive hints.
