How it works...

To better understand the extent to which code has to execute so as to allocate a variable on the heap, we will start with the following simple example:

int main(void){    auto ptr = std::make_unique<int>();}

As shown in the preceding example, we allocate an integer using std::unique_ptr(). We use std::unique_ptr() as our starting point, as this is how most C++ Core Guideline code will allocate memory on the heap.

The std::make_unique() function allocates a std::unique_ptr using the following pseudo logic (this is a simplified example as this doesn't show how custom deleters are handled):

namespace std{    template<typename T, typename... ARGS>    auto make_unique(ARGS... args)    { return std::unique_ptr(new T(std::forward<ARGS>(args)...)); ...

Get Advanced C++ Programming Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.