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 array support

Use case

Allocate shared arrays for buffers.

Explanation

std::make_shared<T[]>(n) allocates an array with shared ownership. Before C++20, we needed shared_ptr<T[]>(new T[n]).

Code

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

int main() {
  auto buffer = std::make_shared<uint8_t[]>(0x1000);

  // https://en.wikipedia.org/wiki/Mach-O
  buffer[0] = 0xCF;
  buffer[1] = 0xFA;
  buffer[2] = 0xED;
  buffer[3] = 0xFE;

  std::cout << "Magic: 0x" << std::hex << static_cast<int>(buffer[3])
            << static_cast<int>(buffer[2]) << static_cast<int>(buffer[1])
            << static_cast<int>(buffer[0]) << "\n";

  return 0;
}

View on GitHub.

Output

$ ./src/c++20/build/std-make_shared-array-support
Magic: 0xfeedfacf