Can anyone explain why this is possible? C ++

1
#include "stdafx.h"
#include <iostream>

using namespace std;

class S
{
public:
    S()
    {

    }

    S& operator=(S&)
    {
        std::cout << "copy assignment" << std::endl;
        return *this;
    }
};

int main()
{
    S s;

    s = S(); // passando um rvalue como argumento para uma função
             // (copy assignment) que só aceita lvalue


    getchar();
    return 0;
}

Could anyone explain why the copy assignment is called in this case? so far as I know, this should only compile if the copy assignment parameter is const S & where it would be possible to pass an rvalue ..

    
asked by anonymous 07.03.2018 / 20:36

1 answer

3

Look, man, here in both GCC 7.3.0 and Clang 5.0.1 this does not even compile for the exact reason you said, the copy assignment signature is wrong:

[phoemur@notebook_lenovo.darkstar ~/cpp/teste]$g++ -o teste teste.cpp -Wall
teste.cpp: In function ‘int main()’:
teste.cpp:24:9: error: cannot bind non-const lvalue reference of type ‘S&’ to an rvalue of type ‘S’
 s = S(); // passando um rvalue como argumento para uma função
     ^~~
teste.cpp:13:8: note:   initializing argument 1 of ‘S& S::operator=(S&)’
 S& operator=(S&)
    ^~~~~~~~
[phoemur@notebook_lenovo.darkstar ~/cpp/teste]$clang++ -o teste teste.cpp -Wall
teste.cpp:24:7: error: no viable overloaded '='
s = S(); // passando um rvalue como argumento para uma função
~ ^ ~~~
teste.cpp:13:8: note: candidate function not viable: expects an l-value for 1st argument
S& operator=(S&)

The signatures of the builders should be the same as the default if it does not compile:

default constructor: X()
copy constructor: X(const X&)
copy assignment: X& operator=(const X&)
move constructor: X(X&&)
move assignment: X& operator=(X&&)
destructor: ~X()
    
08.03.2018 / 02:45