std::move
is used to indicate that an objectt
may be “moved from”, i.e. allowing the efficient transfer of resources fromt
to another object.In particular,
std::move
produces an xvalue expression that identifies its argumentt
. It is exactly equivalent to a static_cast to an rvalue reference type.
在《Data Structures And Algorithm Analysis in Cpp》中学习堆的相关操作,碰到 move
函数的使用,做点笔记。以下是书中小顶堆的插入实现:
/**
* Insert item x, allowing duplicates.
*/
void insert( const Comparable & x ) {
if( currentSize == array.size( ) - 1 )
array.resize( array.size( ) * 2 );
// Percolate up
int hole = ++currentSize;
Comparable copy = x;
array[ 0 ] = std::move( copy );
for( ; x < array[ hole / 2 ]; hole /= 2 )
array[ hole ] = std::move( array[ hole / 2 ] );
array[ hole ] = std::move( array[ 0 ] );
}
原本在编程过程常遇到大量查询并复制等操作,如果元素个数较多或是结构体,可能会增加较大的额外复制开销。使用 move
相当于将对象使用权转交给另一对象,而不用额外的空间去做被复制对象的暂存,节省内存。
#include <iostream>
#include <utility> // move 函数所在头文件
#include <vector>
using namespace std;
int main() {
std::string str = "Hello";
std::vector<std::string> v;
// 使用 push_back(const T&) 重载,
// 表示我们将带来复制 str 的成本
v.push_back(str);
std::cout << "After copy, str is \"" << str << "\"\n";
// 使用右值引用 push_back(T&&) 重载,
// 表示不复制字符串;而是
// str 的内容被移动进 vector
// 这个开销比较低,但也意味着 str 现在可能为空。
v.push_back(std::move(str));
std::cout << "After move, str is \"" << str << "\"\n";
std::cout << "The contents of the vector are \""
<< v[0] << "\", \"" << v[1] << "\"\n";
}
程序输出:
After copy, str is "Hello"
After move, str is ""
The contents of the vector are "Hello", "Hello"