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_unique

Use case

Safe creation of unique_ptr for parsed structures.

Explanation

std::make_unique<T>(args) creates a unique_ptr<T> without using new. It is exception-safe and cleaner than unique_ptr<T>(new T(args)). Equivalent to what make_shared is for shared_ptr.

Code

#include <cstdint>
#include <iostream>
#include <memory>

// https://en.wikipedia.org/wiki/Mach-O
struct LoadCommand {
  uint32_t cmd;
  uint32_t size;

  LoadCommand(uint32_t c, uint32_t s) : cmd(c), size(s) {
    std::cout << "Created LC 0x" << std::hex << cmd << "\n";
  }

  ~LoadCommand() { std::cout << "Destroyed LC 0x" << std::hex << cmd << "\n"; }
};

int main() {
  auto segment = std::make_unique<LoadCommand>(0x19, 72);
  std::cout << "Segment size: " << std::dec << segment->size << "\n";

  return 0;
}

View on GitHub.

Output

$ ./src/c++14/build/std-make_unique
Created LC 0x19
Segment size: 72
Destroyed LC 0x19