【C/C++】move函数的概念与使用

本文深入探讨了C++中的std::move函数,解释了它如何通过转移资源所有权而非复制来提高效率,尤其是在堆操作和数据结构管理中。通过具体实例,展示了move语义在减少复制开销和优化内存使用上的作用。

std::move is used to indicate that an object t may be “moved from”, i.e. allowing the efficient transfer of resources from t to another object.

In particular, std::move produces an xvalue expression that identifies its argument t. 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"
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值