Returning function-local variable as reference
I found this source code:
inline GUID& WString2Guid(wstring src)
{
static GUID result;
HRESULT hr = :开发者_StackOverflow:CLSIDFromString(W2OLE(const_cast<WCHAR*>(src.c_str())), &result);
if (FAILED(hr)) {
//ERROR: The string '%s' is not formatted as a GUID!
throw(E_INVALIDARG);
}
return result;
}
What's the use of returning a reference here? The calling code cannot get a reference anyway because the variable would have left its scope by then. So does this little &
sign make any difference?
To clarify/extend the question: In the same example program, the function is called as
GUID guid = WString2Guid(id); // way 1
If I wanted to make use of the reference, wouldn't I have to call
GUID& guid = WString2Guid(id); // way 2
instead?
And another question; why is the CLSIDFromString
function called with the ::
scope operator before? This would only make any sense if there was another local function declared with the same name, wouldn't it?
No. result
is a static
local variable, so it will exist even after the function exit. Don't confuse this with non-static local variable.
::
in ::CLSIDFromString
tells the compiler to choose CLSIDFromString
from the global namespace, in case if there are many definition of CLSIDFromString
defined in other namespace(s), visible at the call-site.
The variable is static, so it will stay alive. But it's stupid code anyway, it should just return the GUID by value. The scope operator is probably a personal preference of style.
The key bit is the static
keyword. It binds result
to the function itself, not a particular function call. It lives on after a particular call returns, so it's safe to return by reference.
The scope resolution operator (::
) by itself like that makes a call to CLSIDFromString
in the global namespace. Perhaps the code author had another version of that function in his own namespace somewhere. The compiler will tell you if a call to a function is ambiguous and thus you would need to add it. Even if the call isn't ambiguous, it doesn't hurt anything by being there.
to your first question - the local variable is declared as static which means its memory buffer is preserved from one function call to another.
精彩评论