In this code:
SomeClass& some_object = SomeClass();
What does some_object refer to? Is it valid? Or undefined behavior at all?
In this code:
SomeClass& some_object = SomeClass();
What does some_object refer to? Is it valid? Or undefined behavior at all?
This is not valid according to the standard. However, some compilers (notably MSVC) will allow it as an extension.
You are allowed to assign a temporary to a reference-to-const, which will result in the lifetime of that temporary being extended to that of the reference:
{
const SomeClass& some_object = SomeClass();
// more code, some_object is valid
} //some_object is destructed here
It is not valid, as in should not compile:
An rvalue cannot bind to a non-const
lvalue reference.
However some compilers, e.g. MSVC, allow binding rvalues to non-const
lvalue references as a compiler extension.
It doesn't compile at all.
Non-const references (T&
) are not allowed to be bound to temporaries. You can bind temporaries to const T&
or, since C++11, T&&
, though:
const SomeClass& obj = SomeClass();
SomeClass&& obj = SomeClass();