Reference to temporary objects

A

Alexander Stippler

Here my code snippet:

//----------------------

struct Thing
{
};

template <typename T>
struct Wrap
{
operator T &()
{
return t;
} }

T t;
};

Wrap<Thing>
func()
{
return Wrap<Thing>();
}

//------------------------

And here my question:

// 1) Ok, lifetime of returned temporary is bound to "a"
const Wrap<Thing> &a = func();

// 2) Not allowed, why?
Wrap<Thing> &a = func();

// 3) Not ok. "a" references an object that gets destroyed
Thing &a = func()

Here my questions:

why is 2) not allowed?

regarding 3):
I was reading 12.2 in the standard:
"The second context is when a reference is bound to a temporary. The
temporary to which the reference is bound or the temporary that is the
complete object to a subobject of which the temporary is bound persists
for the lifetime of the reference except as specified below".

Well I couldn't see that the "things below" match.
 
R

Rolf Magnus

Alexander said:
Here my code snippet:

//----------------------

struct Thing
{
};

template <typename T>
struct Wrap
{
operator T &()
{
return t;
} }

T t;
};

Wrap<Thing>
func()
{
return Wrap<Thing>();
}

//------------------------

And here my question:

// 1) Ok, lifetime of returned temporary is bound to "a"
const Wrap<Thing> &a = func();
Right.

// 2) Not allowed, why?
Wrap<Thing> &a = func();

Because C++ forbids binding non-const references to temporaries.
// 3) Not ok. "a" references an object that gets destroyed
Thing &a = func()

Right.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,482
Members
44,901
Latest member
Noble71S45

Latest Threads

Top