Re: non-const reference and const reference
On Dec 18, 2:59 pm, George <Geo...@discussions.microsoft.com> wrote:
Hi Abhishek,
I think what you are pointing towards is optimization rather than
convenience. And if it is optimization that you are hinting towards
then is that not what RVO/NRVO would take care of in this case?
What do you mean RVO/NRVO? Looks like there is something you think it is not
fully optimized in the following code provided by Alex before? What are the
points do you think there are issues?
std::string get_file_path();
const std::string& str = get_file_path();
// use str
FILE* f = fopen(str.c_str(), ...);
....
So, instead of making redundant copy of a string, you just
bind a reference to return value of `foo' and use it as long
as you need it.
RVO expands to return value optimization. The idea is when you return
some object from a function by value - the compilers are capable of
optiming away the copy construction of the returned value. This can be
understood by visualizing that the function being called gets an
additional hidden argument (that is same type as the returned object)
and it is used to make all changes to the object passed in instead of
the object that actually undergoes changes before return. Here is an
article by Ayman Shoukry on it - http://msdn2.microsoft.com/en-us/library/ms364057(vs.80).aspx
In the example above - get_file_path() is a function that returns by
value and since that is a temporary (not named object) - it is being
bound to a reference to const 'str'. The lifetime of the temporary is
extended till that of reference 'str'. Now, even if we did not bind
the returned value to a reference to const and instead did a copy
initialization of another string object, for example:
std::string another_string = get_file_path();
this is where the return value optimization kicks in. You would expect
a copy construction of another_string from the returned string object
from get_file_path() but it is optimized away.