Can anyone explain why this is possible? C++

Asked

Viewed 91 times

0

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

Would anyone care to explain to me why copy assignment is called in this case? as 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..

1 answer

2


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 signature of the copy assignment 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&)

Constructors' signatures must be equal to the default if they do 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()
  • Thanks, this is not the first 'anomaly' that I see in the visual c++.

  • 1

    @Strawberryswing if this answer can satisfactorily solve your question, you can mark it as accepted by clicking . This is the biggest thanks you can do

Browser other questions tagged

You are not signed in. Login or sign up in order to post.