【发布时间】:2018-04-04 21:15:13
【问题描述】:
考虑以下几点:
#include <iostream>
using namespace std;
class MyClass {
public:
MyClass(string myMemberInitValue);
const string getMyMember1();
private:
string myMember;
};
MyClass::MyClass(string myMemberInitValue) :
myMember(myMemberInitValue)
{}
const string MyClass::getMyMember1()
{
return myMember;
}
int main()
{
MyClass myObj("Hello World");
const string myVal1 = myObj.getMyMember1(); // Ok
const string &myRef1 = myObj.getMyMember1(); // A reference to an rvalue
...
return 0;
};
通常如果您使用常量reference to a r-value lifetime of the r-value is extended to match the lifetime of the reference...
1.但是如果右值是对象的成员变量呢?
要么复制值,要么引用成员变量,但只要成员变量的值不改变,这都是有效的......
2。所以在我的理解中,值无论如何都必须被复制,对吧?
3.那么const string myVal1 = myObj.getMyMember1() 和const string &myRef1 = myObj.getMyMember1()(编译器行为、性能)有区别吗?
【问题讨论】:
-
您的函数按值返回,这意味着它返回您放入返回表达式中的内容的副本(通常)。理论上,除了
decltype(myRef1)的结果之外,您在 #3 中提到的两个代码之间的行为或性能没有区别 -
@NonCreature0714 该线程似乎没有涵盖这个问题(根本没有提到指针)
-
@NonCreature0714 我看了一下应该回答我的问题,因为它是重复的,并且看不到与成员变量相关的 const 引用的任何内容...你能解释一下为什么你认为我的问题是重复的,以便我能够更清楚地说明差异?
-
@goulashsoup 话虽如此,我尊重 M.M 的专业知识,并为错误地举起错误的旗帜道歉。