What Are Smart Pointers

beginner c++14 memory

Related: Pointers and The Heap

In C++ heap memory must be manually managed by always remembering to call delete for every new in your program. The C++ Standard Library provides two “smart pointer” helper classes that automatically call delete in their destructors: std::unique_ptr and std::shared_ptr. Smart pointer classes and their helper functions are found in the memory header.

#include <iostream>
#include <memory>

class Talker {
public:
  explicit Talker(std::string name) : name_(std::move(name)) {
    std::cout << name_ << " here.\n";
  }
  ~Talker() {
    std::cout <<  name_ << ", signing off.\n";
  }
private:
  std::string name_;
};

int main() {
  Talker* nushi = new Talker("Nushi");
  
  // The std::unique_ptr calls delete for us
  std::unique_ptr<Talker> jose = std::make_unique<Talker>("Jose");

  // We can't forget to call `delete` because we called `new`!
  delete nushi;
}
Nushi here.
Jose here.
Nushi, signing off.
Jose, signing off.


For more C++ By Example, click here.