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