std::unique_ptr expresses exclusive ownership of a dynamically allocated object or array. It automatically releases the resource when its owner leaves scope, removing much of the manual lifetime-management code required by raw pointers. section 2.8 section 10.6
Mistake: copying an exclusive raw pointer
A raw pointer can be copied without transferring ownership. In the Buffer example, b1 and b2 refer to the same object; deleting b1 leaves b2 dangling, and deleting b2 again creates a double-delete failure. The safer version stores the array in std::unique_ptr<int[]> and constructs it with std::make_unique<int[]>(10), so Buffer needs no user-written destructor. section 2.8
Exclusive ownership cannot be copied normally. Transfer it explicitly with std::move: the destination receives ownership and the source becomes effectively empty. Prefer std::make_unique to writing new because it avoids raw pointers and provides better exception safety. section 2.8
Use unique ownership as the default when sharing is unnecessary:
- Choose std::unique_ptr for resources with one owner; use std::shared_ptr only when multiple owners are required. section 2.9
- Replace raw resource pointers incrementally where compatibility permits, and use Boost exclusive-ownership pointers when modern C++ is unavailable. section 10.6
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;
}
Browse the complete Buffer implementation showing array ownership, make_unique construction, and ownership transfer. section 2.8

