Search code examples
c++stringoperator-overloadingrvaluecopy-assignment

Why std::string a; std::string b; a + b = "abc"; OK?


#include <iostream>
#include <string>

int main()
{
    std::string a;
    std::string b;
    a + b = "dadas";
}

PS D:\WeCode\local_c++> & 'c:\Users\z00841303.vscode\extensions\ms-vscode.cpptools-1.5.1\debugAdapters\bin\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\bin\gdb.exe' '--interpreter=mi'

a+b is an rvalue expression. Why can a value be assigned in this way?


Solution

  • It seems one of possible reasons is that ref-specifiers for functions were introduced in the C++ Standard after the class template std::basic_string was defined in the C++ Standard. Otherwise the assignment operator could be declared for example like

    std::basic_string & operator( const std::basic_string & ) &;
    

    Here is a demonstration program that shows how to suppress an assignment to rvalue.

    #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!
    }
    

    Anpther reason is to allow chaining operations that defined as functions for user-defined types.