2

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?

Felix Dombek
  • 13,664
  • 17
  • 79
  • 131

4 Answers4

11

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.

Nawaz
  • 353,942
  • 115
  • 666
  • 851
1

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.

Cat Plus Plus
  • 125,936
  • 27
  • 200
  • 224
  • 2
    The scope operator is often used to indicate that you really intend to call a Windows API function directly and not a framework wrapper. – Bo Persson Jul 25 '11 at 15:16
1

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.

Michael Kristofik
  • 34,290
  • 15
  • 75
  • 125
0

to your first question - the local variable is declared as static which means its memory buffer is preserved from one function call to another.

NirMH
  • 4,769
  • 3
  • 44
  • 69