liveBook · Manning

Make_unique

As explained in 100 C++ Mistakes and How to Avoid Them

std::make_unique is a C++ standard-library function template that creates and returns a std::unique_ptr with exception-safe allocation and construction.

std::make_unique creates an object or array and returns a std::unique_ptr that manages exclusive ownership. Prefer it to writing new directly: it improves exception safety, avoids raw pointers, and keeps allocation and construction together. section 2.8

The practical mistake is managing one resource through copied raw pointers. Both pointers may appear valid, but deleting them separately causes double deletion. unique_ptr makes ownership explicit and prevents accidental copying. section 2.8

Listing 2.15 A botched attempt at managing an exclusive resource
struct Buffer {
private:
    int* data;
public:
    Buffer() : data(new int[10]) {}
    ~Buffer() { delete[] data; }
};
 
int main() {
    Buffer* b1 = new Buffer();
    Buffer* b2 = b1;                                         #1
    if (b1)
        delete b1;                                           #2
    if (b2)
        delete b2;                                           #3
    return 0;
}

A copied Buffer pointer leaves two owners and leads to repeated deletion. section 2.8

Listing 2.16 Implementing exclusive ownership using unique_ptr
struct Buffer {
private:
    std::unique_ptr<int[]> data;                            #1
public:
    Buffer() : data(std::make_unique<int[]>(10)) {}         #2
};
 
int main() {
    auto b1 = std::make_unique<Buffer>();                   #3
    auto b2 = std::move(b1);                                #4
    return 0;
}

The corrected pattern uses make_unique for both an array member and a Buffer object, then transfers ownership with std::move. section 2.8

How 100 C++ Mistakes and How to Avoid Them covers it

How deep it goes
Shows object and array construction, ownership transfer, and double-deletion consequences, but does not develop implementation internals.
Examples
Uses a Buffer with dynamically allocated array storage and transfers a uniquely owned Buffer between b1 and b2.
What it assumes
Assumes familiarity with new, delete, pointers, and dynamic resources while teaching exclusive ownership through unique_ptr.
What you can do after
Apply it via std::make_unique and std::unique_ptr to construct resources and transfer ownership safely.
How it connects
Connects make_unique to unique_ptr, exclusive ownership, raw pointers, dynamic allocation, and std::move.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of 100 C++ Mistakes and How to Avoid Them. The section links point to the parts of the book it draws on.