mirror of
https://github.com/AnthonyCalandra/modern-cpp-features.git
synced 2025-12-17 01:54:36 +03:00
Better explanation for std::move.
This commit is contained in:
4
CPP11.md
4
CPP11.md
@@ -648,7 +648,7 @@ In C++14, `decltype(auto)` can be used instead.
|
||||
## C++11 Library Features
|
||||
|
||||
### std::move
|
||||
`std::move` indicates that the object passed to it may be moved, or in other words, moved from one object to another without a copy. The object passed in should not be used after the move in certain situations.
|
||||
`std::move` indicates that the object passed to it may have its resources transferred. Moves can often be more efficient than copies. Using objects that have been moved from should be used with care, as they can be left in an unspecified state (see: [What can I do with a moved-from object?](http://stackoverflow.com/questions/7027523/what-can-i-do-with-a-moved-from-object)).
|
||||
|
||||
A definition of `std::move` (performing a move is nothing more than casting to an rvalue):
|
||||
```c++
|
||||
@@ -660,7 +660,7 @@ typename remove_reference<T>::type&& move(T&& arg) {
|
||||
|
||||
Transferring `std::unique_ptr`s:
|
||||
```c++
|
||||
std::unique_ptr<int> p1 {new int{0}};
|
||||
std::unique_ptr<int> p1 {new int{0}}; // in practice, use std::make_unique
|
||||
std::unique_ptr<int> p2 = p1; // error -- cannot copy unique pointers
|
||||
std::unique_ptr<int> p3 = std::move(p1); // move `p1` into `p3`
|
||||
// now unsafe to dereference object held by `p1`
|
||||
|
||||
@@ -1460,7 +1460,7 @@ In C++14, [decltype(auto)](#decltypeauto) can be used instead.
|
||||
## C++11 Library Features
|
||||
|
||||
### std::move
|
||||
`std::move` indicates that the object passed to it may be moved, or in other words, moved from one object to another without a copy. The object passed in should not be used after the move in certain situations.
|
||||
`std::move` indicates that the object passed to it may have its resources transferred. Moves can often be more efficient than copies. Using objects that have been moved from should be used with care, as they can be left in an unspecified state (see: [What can I do with a moved-from object?](http://stackoverflow.com/questions/7027523/what-can-i-do-with-a-moved-from-object)).
|
||||
|
||||
A definition of `std::move` (performing a move is nothing more than casting to an rvalue):
|
||||
```c++
|
||||
@@ -1472,7 +1472,7 @@ typename remove_reference<T>::type&& move(T&& arg) {
|
||||
|
||||
Transferring `std::unique_ptr`s:
|
||||
```c++
|
||||
std::unique_ptr<int> p1 {new int{0}};
|
||||
std::unique_ptr<int> p1 {new int{0}}; // in practice, use std::make_unique
|
||||
std::unique_ptr<int> p2 = p1; // error -- cannot copy unique pointers
|
||||
std::unique_ptr<int> p3 = std::move(p1); // move `p1` into `p3`
|
||||
// now unsafe to dereference object held by `p1`
|
||||
|
||||
Reference in New Issue
Block a user