Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > C++ > Reference to temporary objects

Reply
Thread Tools

Reference to temporary objects

 
 
Alexander Stippler
Guest
Posts: n/a
 
      03-17-2006
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.
 
Reply With Quote
 
 
 
 
Rolf Magnus
Guest
Posts: n/a
 
      03-17-2006
Alexander Stippler wrote:

> 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.

 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
anonymous array of strings // ("taking address of temporary"- how long is temporary valid?) anon.asdf@gmail.com C++ 7 02-12-2008 10:58 AM
class objects, method objects, function objects 7stud Python 11 03-20-2007 06:05 PM
Temporary objects as arguments to constructor calls szaki@colbud.hu C++ 5 06-24-2005 01:33 PM
Address of temporary objects Ariel C++ 2 11-03-2004 08:20 AM
Temporary objects as constructor arguments? Andy Buckley C++ 5 08-26-2004 01:32 AM



Advertisments