0

In this code:

SomeClass& some_object = SomeClass();

What does some_object refer to? Is it valid? Or undefined behavior at all?

Therhang
  • 825
  • 1
  • 9
  • 15

3 Answers3

2

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
TartanLlama
  • 63,752
  • 13
  • 157
  • 193
1

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.

Emil Laine
  • 41,598
  • 9
  • 101
  • 157
0

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();
cadaniluk
  • 15,027
  • 2
  • 39
  • 67