Search code examples
c++visual-c++mfcobject-lifetime

What happens when a function returns a CString?


I have a very thorough understanding of memory and pointers, but I need a little refresher with regard to exactly how C++ manages some objects under the covers.

Consider the following code:

void Test()
{
    LPCTSTR psz = (LPCTSTR)GetString();
}

CString GetString()
{
    return CString(_T("abc"));
}

Questions:

  1. Could someone flesh out how GetString() can return a local object and it still be valid in the caller?

  2. Since the result of GetString() is not stored anywhere, how is it deleted?

  3. Is psz guaranteed to be "safe" to use for the entirety of the Test() function?

Sorry for using old classes for this example, but that's what I'm working with right now.


Solution

    1. GetString returns a copy of a local object (though the actual copying may be elided, and the local temporary returned directly).

    2. The return value of GetString() is a temporary. Like most temporaries, it's automatically destroyed at the end of a full expression (essentially, at the semicolon).

    3. psz gets a pointer to the buffer managed by that temporary. Once the temporary is destroyed, psz becomes dangling. Any attempt to actually use it would exhibit undefined behavior.