Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

std::make_shared

Use case

Efficient creation of shared pointers.

Explanation

std::make_shared<T>(arg) creates a shared_ptr in one allocation (managed object + control block). More efficient and exception-safe than shared_ptr<T>(new T(arg)) (which does 2 allocations).

Code

#include <iostream>
#include <memory>

struct Symbol {
  const char *name;
  Symbol(const char *n) : name(n) { std::cout << "Created.\n"; }
  ~Symbol() { std::cout << "Destroyed.\n"; }
};

int main() {
  auto sym = std::make_shared<Symbol>("_main");
  auto copy = sym;
  std::cout << "Ref count: " << sym.use_count() << "\n";
  return 0;
}

View on GitHub.

Output

$ ./src/c++11/build/std-make_shared
Created.
Ref count: 2
Destroyed.