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
  • 154,301
  • 39
  • 440
  • 740
MistyD
  • 16,373
  • 40
  • 138
  • 240

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
  • 60,038
  • 8
  • 155
  • 203