如何将临时对象作为非常量引用传递给成员函数?

问题描述

我们正在创建一个类,该类旨在从当前模块发送信息(具体信息与此问题无关)。创建此类型的对象,并用需要发送的部分数据填充该对象,然后将其传递到(不同类)成员函数中。该函数为对象提供其余数据,然后通过对象本身的调用触发发送。因为传递的信息是动态的,所以目的是使信息传递对象是临时的,使用最新数据创建。我们排队的设计在下面的摘录源代码中,但是gcc / C ++不允许这样做,从而显示错误。

问题是,如何使用可以被调用的函数修改和使用的临时对象(很好的避免内存泄漏)来实现预期的行为?

gcc编译器错误:

infoxfer.cpp: In function ‘int main()’:
infoxfer.cpp:54:43: error: cannot bind non-const lvalue reference of type ‘XferInfo&’ to an rvalue of type ‘XferInfo’
   51 |     callee.doSomething("Something param",XferInfo("from main()"));
      |                                           ^~~~~~~~~~~~~~~~~~~~~~~
infoxfer.cpp:36:62: note:   initializing argument 2 of ‘void Callee::doSomething(const string&,XferInfo&)’
   33 |     void doSomething(const string& somethingParam,XferInfo& xferInfo)
      |                                                    ~~~~~~~~~~^~~~~~~~

提取的示例代码:
infoxfer.cpp:

#include <iostream>
using std::cout;
using std::endl;

#include <string>
using std::string;

class XferInfo
{
private:
    const string mCallerInfo;
    string mCalleeInfo;

public:
    XferInfo(const string& callerInfo) : mCallerInfo(callerInfo)
    {}

    void setCalleeInfo(const string& calleeInfo)
    {
        mCalleeInfo = calleeInfo;
    }

    void sendData()
    {
        // simulate sending data
        cout << mCallerInfo << " | " << mCalleeInfo << endl;
    }
};

class Callee
{
public:
    void doSomething(const string& somethingParam,XferInfo& xferInfo)
    {
        // complete data for xfer
        xferInfo.setCalleeInfo(somethingParam);

        // simulate doing something
        cout << "do something" << endl;

        // send the complete info
        xferInfo.sendData();
    }
};

int main()
{
    cout << "start" << endl;

    Callee callee;
    callee.doSomething("Something param",XferInfo("from main()"));

    cout << "end" << endl;

    return 0;
}

解决方法

如评论中所述,您可以简单地将doSomething函数更改为接受rvalue reference到传递的XferInfo对象(使用双&&):>

    void doSomething(const string& somethingParam,XferInfo&& xferInfo)
    {
        // complete data for xfer
        xferInfo.setCalleeInfo(somethingParam);
        // ... and so forth ...

从链接的cppreference页面:

右值引用可用于延长临时项的生存期 对象(请注意,对const的左值引用可以延长 也可以使用临时对象,但无法通过它们进行修改)

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...