Temp variables and const references

Hi guys, I've a question that I searched on the web but it is still a little confusing. I read that by adding "const" to a reference prolongs the lifetime for the local variables in the function. Here are 2 codes.

1
2
3
4
5
  const free_throws & clone2(free_throws & ft)
{
	const free_throws & newguy = ft;
	return newguy;
}


and...

1
2
3
4
5
6
const free_throws & clone2(free_throws & ft)
{
        free_throws newguy; 
        newguy = ft; 
        return newguy;
}


Does the 1st code solve the problem created by the 2nd code? I was reading this C++ Primer Plus and it came out with this 2nd example. And then while searching I chance upon this website:

http://stackoverflow.com/questions/4670137/prolonging-the-lifetime-of-temporaries

Can anyone help me with this?
Last edited on
I read that by adding "const" to a reference prolongs the lifetime for the local variables in the function.

It prolongs the lifetime of a temporary object. In your code you don't have any temporary objects.

The problem with the second function is that newguy object will go out of scope at the end of the function, so the caller of the function end up with a reference to a non-existing object.

The first code you can safely do something like this:
1
2
free_throws obj;
const free_throws& ref = clone2(obj);
Here ref will refer to obj that was defined on the line above.

But if you instead pass in a temporary object to the function, like this:
 
const free_throws& ref = clone2(free_throws());
It will not work because ref will refer to the temporary object, and after that line has ended the temporary object no longer exist.
Uh

const free_throws& ref = clone2(free_throws()), the "free_throws()" here means a function? Sorry but I don't understand about free_throws() being an object.

And thank you for your answer! :)
Last edited on
No, it uses the default constructor to create a free_throws object.
Last edited on
const reference does not prolong anything. The special thing about const reference is that a temporary variable may be created if and only if the assigned type is not a reference of that particular type and there is a constructor for the assigned type.

const std::string &str = "abc"; // the same as without &

1
2
std::string str = "abc";
const std::string &r_str = str; // Only alias / the same life time as str 
Thanks for the answer!

P.S. - I haven't read till constructors and destructors yet, but I think this might come in handy in the future!
Topic archived. No new replies allowed.