Modern C++ › C++11
Move Semantics and unique_ptr
Transfer resources instead of copying them, and use unique_ptr for safe exclusive ownership.
Since C++11 intermediate #move#rvalue-reference#unique_ptr#smart-pointers#ownership
Explanation
An rvalue reference (T&&) binds to temporaries. A move constructor/assignment takes a T&& and steals the resource, leaving the source valid but empty. std::move(x) is only a cast to an rvalue: it signals “I no longer need x”.
std::unique_ptr<T> is the replacement for auto_ptr: exclusive ownership, move-only. Copying is a compile error, so ownership transfer is always explicit.
Example
#include <iostream>
#include <memory>
#include <utility>
#include <vector>
struct Widget { ~Widget() { std::cout << "destroyed\n"; } };
int main() {
std::unique_ptr<Widget> a(new Widget);
// std::unique_ptr<Widget> b = a; // error: copy deleted
std::unique_ptr<Widget> b = std::move(a); // explicit transfer
std::cout << (a ? "a owns\n" : "a is null\n");
std::vector<std::unique_ptr<Widget>> v; // fine, unlike auto_ptr
v.push_back(std::move(b));
return 0;
}
Pitfalls
- Do not use an object after
std::moveing from it, except to assign or destroy it. std::moveon aconstobject silently falls back to a copy.- Mark move operations
noexcept, orstd::vectorwill copy instead of move on reallocation.
Legacy vs modern
auto_ptr (C++98) |
unique_ptr (C++11) |
|
|---|---|---|
| Copy | compiles, transfers ownership | does not compile |
| In containers | unsafe | supported |
| Arrays | no | unique_ptr<T[]> |
| Custom deleter | no | yes |
In C++14, prefer std::make_unique<Widget>() over new.
Exercises
1. Convert std::auto_ptr<Foo> p(new Foo); std::auto_ptr<Foo> q = p; to modern C++.
std::unique_ptr<Foo> p(new Foo);
std::unique_ptr<Foo> q = std::move(p);