temporary-objects

Why not non-const reference to temporary objects? [duplicate]

吃可爱长大的小学妹 提交于 2019-11-26 01:36:14
C++ allows assignment of temporary objects only to const reference. It wont allow assignement of temporary objects to reference. For example: String& a = String("test"); // Error const String& a = String("test"); // Ok Everywhere I google for this result, i only see the following answers Modifying temporary objects would cause unidentifiable problems Modifying temporary objects is dangerous At some point of time, you will forget it is a temporary variable It's been said, temporary objects vanishes after the statement. So you should not modify it. If C++, is so keen in blocking modifying the

Non-const reference bound to temporary, Visual Studio bug?

别来无恙 提交于 2019-11-26 01:21:18
问题 I ran into this while compiling some portable code in gcc . Basically this strange code compiles in Visual studio which really just blows my mind: class Zebra {int x;}; Zebra goo() {Zebra z; return z;} void foo(Zebra &x) { Zebra y; x = y; foo(goo()); } Visual studio lets this one fly. gcc will catch this as a compile error. Interestingly, If you typedef Zebra to int, VC++ will complain. Quite contradictory behavior. Thoughts? 回答1: This is old extension to Visual Studio, the only reference I

Why not non-const reference to temporary objects? [duplicate]

让人想犯罪 __ 提交于 2019-11-26 00:54:55
问题 Possible Duplicate: Does a const reference prolong the life of a temporary? prolonging the lifetime of temporaries C++ allows assignment of temporary objects only to const reference. It wont allow assignement of temporary objects to reference. For example: String& a = String(\"test\"); // Error const String& a = String(\"test\"); // Ok Everywhere I google for this result, i only see the following answers Modifying temporary objects would cause unidentifiable problems Modifying temporary