我读了this,然后试着写了一个类(一个虚拟字符串类),在那里我可以试着看到右值引用的好处,就像那个文档中解释的那样。
但是我没有看到我的+(&&)运算符被调用。理论上&& based +运算符应该被调用来捕获对str2 +“test”+ str2表达式的(str2 +“test”)部分的右值引用。
代码如下:
class Test
{
public:
Test()
{
cout << "\nctor called";
}
Test(Test& obj)
{
cout << "\ncopy ctor called";
}
Test(Test&& rvalue_exp)
{
cout << "\nrvalue exp called";
}
Test operator+(const char* str)
{
cout << "\noperator + called " << str;
}
Test operator+(const Test& str)
{
cout << "\noperator +& called";
}
Test operator+(Test&& str)
{
cout << "\noperator +&& called";
}
void operator=(const Test& str)
{
cout << "\noperator + called";
}
};
int main()
{
cout<<"Hello World";
Test str, str2;
str = str2 + "test" + str2;
return 0;
}
output:
Hello World
ctor called
ctor called
operator + called test
operator +& called
operator + called
字符串
所以我的问题是,根据我链接的文档中的理论,用户如何从我的+运算符中受益?
1条答案
按热度按时间evrscar21#
你混淆了
字符串
和
型
str = str2 + "test" + str2;
在右边没有右值,operator+
的参数。要呼叫您的操作员,请尝试以下操作:
型
还要注意,你的操作符返回了一个无效的类型,它应该返回一个引用。
你的操作符承诺返回值,但实际上并不返回任何东西。这导致了未定义的行为。