Temporaries bind to const reference

K

kaede

Hi all,

I would like to know if the following code is valid and not
ill-formed.

Data getData()
{
return Data(1, 2, 3);
}

void processData(const Data& data)
{
// ... work with data ...
}


// ... in some code somewhere ...
processData( getData() );

Will this const reference initialized with getData() [temporaries]
make that temporary value live for the lifetime of the reference
itself?

Thanks,
Kaede
 
K

Kevin Goodsell

kaede said:
Hi all,

I would like to know if the following code is valid and not
ill-formed.

Data getData()
{
return Data(1, 2, 3);
}

void processData(const Data& data)
{
// ... work with data ...
}


// ... in some code somewhere ...
processData( getData() );

The code is valid (as far as I can tell - it's incomplete, after all).
Will this const reference initialized with getData() [temporaries]
make that temporary value live for the lifetime of the reference
itself?

I don't think that's precisely correct. Temporaries (usually) live until
the end of the full expression in which they are created. There are
exceptions to this, but I don't believe they apply here. In this case,
the full expression ends *after* the call to processData() returns,
therefore it has nothing to do with references - that temporary would
live until the function completed whether you used a reference or not.

-Kevin
 

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

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,012
Latest member
RoxanneDzm

Latest Threads

Top