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?
const
goo
Is it wrong with UB and MSVS, or is it normal?
It's illegal. The corresponding implementation diagnoses it (that is, it should at least warn), but MSVC ++ allows it as an extension.
, , IIRC - , , - : , MSV++, , ++ , , , , , , . , () , , ? , , , , .
, -, 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&)’