C++返回值需不需要使用move来调用移动构造?

博客主要探讨C++中函数返回对象的情况。编译器会自动优化,在函数调用处直接构造对象,直接返回时函数内对象地址和接收对象地址相同,无需调用移动构造。而使用move会调用移动构造,速度反而更慢。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

答案

不需要

原因

编译器自动优化,会直接在函数调用处构造该对象。

#include <iostream>
using namespace std;
class TestMove{
public:
    TestMove(){
        cout<<"Constructor"<<endl;
    }
    TestMove(const TestMove &&other){
        cout<<"Move constructor"<<endl;
    }
    TestMove(const TestMove &other){
        cout<<"Copy constructor"<<endl;
    }
    ~TestMove(){
        cout<<"Deconstrcutor"<<endl;
    }
};

TestMove func(){
    cout<<"no Move"<<endl;
    TestMove testMove;
    cout << "func::TestMove:" << &testMove << endl;
    return testMove;
}

TestMove func_with_move(){
    cout<<"with move"<<endl;
    TestMove testMove;
    return std::move(testMove);
}

int main(){
    TestMove tm1 = func();
    cout << "main::tm1:" << &tm1 << endl;
    cout<<endl;
    TestMove tm2 = func_with_move();
    cout<<endl;
    return 0; 
}

在这里插入图片描述
当直接返回时,发现函数内对象地址和接收对象地址一样,证明编译器优化会在接受对象处直接构造,甚至不需要调用移动构造。

当使用move时,会理所应当的调用移动构造,相比直接返回甚至更慢。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值