#include <iostream>
#include <string>
int main()
{
std::string a;
std::string b;
a + b = "dadas";
}
PS D:\WeCode\local_c++> & 'c:\Users\z00841303.vscode xtensions\ms-vscode.cpptools-1.5.1\debugAdapters in\WindowsDebugLauncher.exe' '--stdin=Microsoft-MIEngine-In -1vidcjmy.adn''--stdout=Microsoft-MIEngine-Out-ur4nmbvf.4bj''--stderr=Microsoft-MIEngine-Error-kdush30f.pk5''--pid=Microsoft-MIEngine-Pid-5hgspuj4.obh' '--dbgExe=D:\Program Files\mingw\MinGW in\gdb.exe' '--interpreter=mi'
a+b 是右值表达式。为什么可以这样赋值?
原因似乎是在 C++ 标准中定义了类模板 std::basic_string
之后,C++ 标准中引入了函数的
ref-specifiers。否则,可以声明赋值运算符,例如
std::basic_string & operator( const std::basic_string & ) &;
这是一个演示程序,展示如何抑制对右值的赋值。
#include <iostream>
int main()
{
struct A
{
A( int x = 0 ) : x( x ) {}
A &operator =( const A &a ) &
{
x = a.x;
return *this;
}
static A f( const A &a )
{
return a;
}
int x;
};
A a1( 10 );
std::cout << ( a1 = A::f( A( 20 ) ) ).x << '\n';
// A::f( A( 20 ) ) = a1; <=== compiler error!
}