std::moveis used to indicate that an objecttmay be “moved from”, i.e. allowing the efficient transfer of resources fromtto another object.In particular,
std::moveproduces 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"
本文深入探讨了C++中的std::move函数,解释了它如何通过转移资源所有权而非复制来提高效率,尤其是在堆操作和数据结构管理中。通过具体实例,展示了move语义在减少复制开销和优化内存使用上的作用。
2万+

被折叠的 条评论
为什么被折叠?



