返回函数局部变量作为参考 [英] Returning function-local variable as reference
问题描述
我发现这个源代码:
inline GUID& WString2Guid(wstring src)
{
static GUID result;
HRESULT hr = ::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
如果我想使用引用,
GUID& guid = WString2Guid(id); // way 2
?
另一个问题;为什么 :: 范围操作符之前调用
CLSIDFromString
如果有另一个局部函数声明有相同的名字,这将是有意义的,不是吗?
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?
推荐答案
result
是一个 static
局部变量,因此即使在函数退出后它也会存在。不要将其与非静态局部变量混淆。
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.
:: :CLSIDFromString
告诉编译器从全局命名空间中选择 CLSIDFromString
,如果存在 CLSIDFromString
在其他命名空间中定义,在调用站点可见。
::
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.
这篇关于返回函数局部变量作为参考的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!