C++:C++ Smart Pointers and RAII Memory Management (C++11)
C++•Memory Management

C++ Smart Pointers and RAII Memory Management (C++11)

Say goodbye to raw new and delete. Modern C++ relies on smart pointers for automatic deterministic memory cleanup.

Syntax

#include <memory> auto ptr = std::make_unique<Type>(args); auto shared = std::make_shared<Type>(args);

Parameters & Values

Key components and acceptable values for this structure:

ParameterTypeDescription
std::unique_ptrSmart PointerZero-overhead exclusive ownership pointer; cannot be copied, only moved.
std::shared_ptrSmart PointerReference-counted shared ownership pointer.

Ready-to-Run Code Example

Executable in Compilra

Run this complete, working example directly without installing C++ locally:

#include <iostream>
#include <memory>
#include <string>

class Resource {
public:
    Resource() { std::cout << "  [Resource] Allocated in heap memory.\n"; }
    ~Resource() { std::cout << "  [Resource] Destructor called: freed automatically!\n"; }
    void process() { std::cout << "  [Resource] Processing work.\n"; }
};

int main() {
    std::cout << "Entering scoped block:\n";
    {
        // Allocate unique_ptr using std::make_unique
        std::unique_ptr<Resource> res = std::make_unique<Resource>();
        res->process();
        // Memory automatically freed when res exits scope
    }
    std::cout << "Exited scoped block cleanly (Zero memory leaks).\n";

    return 0;
}
Expected Output:
Entering scoped block:
  [Resource] Allocated in heap memory.
  [Resource] Processing work.
  [Resource] Destructor called: freed automatically!
Exited scoped block cleanly (Zero memory leaks).

How It Works: Step-by-Step

  • Lines 5-9: Defines Resource with constructor and destructor to observe lifecycle.
  • Lines 16-18: std::make_unique allocates resource and binds to scoped pointer.
  • Line 20: Destructor automatically triggers at closing brace } without delete.

Key Concepts

  • Resource Acquisition Is Initialization (RAII) ties resource lifespan to object scope.
  • std::unique_ptr has zero runtime overhead compared to a raw pointer.
  • Never manually call delete when using smart pointers.

Common Mistake: Using raw new and delete in modern C++

Raw delete is prone to memory leaks if an exception interrupts execution before delete is called.

❌ Incorrect
Resource* r = new Resource();
// If an error happens here, r leaks!
delete r;
✅ Correct
auto r = std::make_unique<Resource>(); // 100% leak-proof

Related C++ Tutorials & Compiler

Run and test C++ on Compilra

Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.

C++ Online Compiler