Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning function-local variable as reference

I found this source code:

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

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?

like image 418
Felix Dombek Avatar asked Mar 11 '26 11:03

Felix Dombek


2 Answers

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.

like image 120
Nawaz Avatar answered Mar 14 '26 00:03

Nawaz


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.

like image 41
Cat Plus Plus Avatar answered Mar 14 '26 02:03

Cat Plus Plus



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!