Labs ICT
Pro Login

Smart Pointers

Smart pointers are C++11's answer to manual memory management. They are wrapper classes that automatically delete the object they own when they go out of scope. No more forgetting to call delete — the destructor handles it for you.

unique_ptr

A unique_ptr has exclusive ownership of the object. You cannot copy it — only move it. When the unique_ptr goes out of scope, the object is deleted automatically.

#include <iostream>
#include <memory>

int main() {
  std::unique_ptr<int> ptr = std::make_unique<int>(42);

  std::cout << "Value: " << *ptr << "\n";

  std::unique_ptr<int> moved = std::move(ptr);

  if (!ptr) {
    std::cout << "Original pointer is now null\n";
  }

  std::cout << "Moved value: " << *moved << "\n";
  return 0;
}

Use std::make_unique to create a unique pointer. It is safer and more efficient than using new directly. After moving, the original pointer becomes null.

shared_ptr

A shared_ptr uses reference counting. Multiple smart pointers can share ownership of the same object. The object is deleted when the last shared_ptr pointing to it is destroyed.

#include <iostream>
#include <memory>

int main() {
  std::shared_ptr<int> a = std::make_shared<int>(100);
  std::shared_ptr<int> b = a;
  std::shared_ptr<int> c = a;

  std::cout << "Value via a: " << *a << "\n";
  std::cout << "Value via b: " << *b << "\n";
  std::cout << "Reference count: " << a.use_count() << "\n";

  b.reset();
  std::cout << "After resetting b, count: " << a.use_count() << "\n";
  return 0;
}

Use std::make_shared to create shared pointers. The reference count increases with each copy and decreases when a shared pointer is destroyed or reset. When it hits zero, the object is freed.

weak_ptr

A weak_ptr holds a non-owning reference to an object managed by shared_ptr. It does not increase the reference count. Use it to break circular references that would otherwise cause memory leaks.

#include <iostream>
#include <memory>

int main() {
  std::shared_ptr<int> shared = std::make_shared<int>(42);
  std::weak_ptr<int> weak = shared;

  std::cout << "Shared count: " << shared.use_count() << "\n";

  if (auto locked = weak.lock()) {
    std::cout << "Value through weak: " << *locked << "\n";
  }

  shared.reset();

  if (weak.expired()) {
    std::cout << "Object has been deleted\n";
  }
  return 0;
}

To access the object through a weak_ptr, call lock() which returns a shared_ptr. If the object was already deleted, lock() returns null.