Why assign a return value to a reference?
I'm looking over some code, and all the calls to a function returning a string are assigned to a reference. The function prototype something like:
std::string GetPath(const std::string& top);
and it's used as
std::string& f =开发者_运维知识库 GetPath(cw);
or
const std::string& f = GetPath(cw);
Why would one use a reference here instead of
std::string f = GetPath(cw);
If the function returned a reference (which it doesn't) then you might want to assign the return value to a reference in order to keep "up to date" with any changes to that object. The reference returned would have to be to an object with a lifetime that extended beyond the end of the function.
Or (if the returned reference was not-const
) because you wanted to keep a reference to the object to mutate it as a subsequent point. (If you wanted to mutate it immediately you would do it directly, no need to store the reference.)
As the function returns a value you could assign it to a const
reference (to a non-const
reference would be illegal) and extend the object's lifetime to the lifetime of the reference. However the effect would be exactly the same (const
aside) as storing the value in a object directly.
Any thought that it might be less efficient may well prove unfounded and you can qualify the object with const
if you want as well. (Most compilers eliminate the implied temporary and construct the return value in the object being initialized.)
As the object type is returned from the function by value it must be copyable so this is no reason to use a reference because of a concern that it isn't.
This is probably an overzealous optimization aimed at cases where function being called returns a reference, as in:
const std::string& func();
...
const std::string& tmp = func();
...
to save on string copy.
Ok, it's completely pointless. And looks awful. And not valid c++. Just don't do it.
Edit: for better understanding of what I mean
reference & var = funcNotReturningReference(); //invalid C++
const reference & cvar = funcNotReturningReference(); //silly C++, no saving costs (reference to temporary stops temporary from being released, but this code does not help anything)
精彩评论