2

I am currently using VS2012 and was expecting statement B in this code to fail since we are passing a temp which is a constant to the assignment operator method in the foo class. Surprisingly that doesnt fail why is that ? Statement A fails and that is fine. Why doesnt statement B fail ?

struct foo
{
    int a;
    foo& operator=(foo& that)
    {
        a=12;
        return *this;
    }
};

int main()
{
    const foo a;
    foo b;
    //b = a;      //statement A
    b = foo();    //Statement B
}
Shafik Yaghmour
  • 148,593
  • 36
  • 425
  • 712
MistyD
  • 14,915
  • 32
  • 126
  • 215

1 Answers1

5

This works because VC++, with language extensions enabled, is not standard compliant and allows binding a non-const lvalue reference to a temporary.

After adding a default constructor in foo, both GCC and Clang issue an appropriate error message:

main.cpp:18:7: error: no viable overloaded '='

  b = foo();    //Statement B
  ~ ^ ~~~~~

main.cpp:6:10: note: candidate function not viable: expects an l-value for 1st argument

foo& operator=(foo&)
     ^
Columbo
  • 58,324
  • 8
  • 149
  • 196