正常
std::move (C++11)
In a Nutshell
It force-casts an lvalue to an rvalue reference, telling the compiler "this object's resources are up for grabs" — which triggers move construction or move assignment and avoids a deep copy.
Header
#include <utility>
Core API Quick Reference
| Operation | Signature | Description |
|---|---|---|
| Move cast (since C++14) | template<class T> constexpr std::remove_reference_t<T>&& move(T&& t) noexcept; | Converts the object t to an rvalue reference (xvalue) |
| Perfect forwarding | template<class T> T&& forward(typename std::remove_reference<T>::type& t) noexcept; | Preserves the value category in forwarding-reference scenarios; equivalent to std::move for rvalue arguments and to pass-by-reference for lvalues |
| Conditional move | template<class T> typename std::conditional<...>::type move_if_noexcept(T& t) noexcept; | Converts to an rvalue if the move constructor is non-throwing; otherwise returns an lvalue |
Minimal Example
C++
#include <iostream>
#include <string>
#include <utility>
#include <vector>
// Standard: C++11
int main() {
std::string str = "Hello";
std::vector<std::string> v;
v.push_back(str); // copy
v.push_back(std::move(str)); // move; str is left in a valid but unspecified state
std::cout << v[0] << " " << v[1] << "\n";
std::cout << "str empty: " << str.empty() << "\n";
}Embedded Suitability: High
- Zero-overhead abstraction:
std::moveis essentially astatic_cast, done at compile time with no runtime cost - Avoids deep copies: when passing large buffers (such as
std::vector<uint8_t>orstd::string), it significantly cuts both RAM usage and CPU overhead - Pairs with custom resource classes: can be used to transfer ownership of raw pointers (in combination with RAII), replacing manual resource handover
- Note that a moved-from object is in a "valid but unspecified" state: you can no longer read its value — you can only assign to it or destroy it
Compiler Support
| GCC | Clang | MSVC |
|---|---|---|
| 4.6 | 3.0 | 19.0 |
See Also
Some content is adapted from cppreference.com, used under the CC-BY-SA 4.0 license