Can temporary connections bind to non-constant links?

I wrote the following code to check this:

struct X
{
   char* x;
   X()
   {
      x = new char('a');
   }
   ~X()
   {
      *x = 'b';
      delete x;
   }
};

void foo(const X& x)
{
}
void goo(X& x)
{
}

int main()
{
   foo(X());
   goo(X());
}

Destructors for temporary are called after the exit of both functions, but I thought you could bind the temporary link to const. Why goodoes it work then?

Is it wrong with UB and MSVS, or is it normal?

+5
source share
2 answers

It's illegal. The corresponding implementation diagnoses it (that is, it should at least warn), but MSVC ++ allows it as an extension.

, , IIRC - , , - : , MSV++, , ++ , , , , , , . , () , , ? , , , , .

+3

, -, MS. , GCC 4.3.4 :

prog.cpp: In function ‘int main()’:
prog.cpp:25: error: invalid initialization of non-const reference of type ‘X&’ from a temporary of type ‘X’
prog.cpp:18: error: in passing argument 1 of ‘void goo(X&)’
+1

All Articles