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
