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:
Could someone flesh out how GetString()
can return a local object and it still be valid in the caller?
Since the result of GetString()
is not stored anywhere, how is it deleted?
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.
GetString
returns a copy of a local object (though the actual copying may be elided, and the local temporary returned directly).
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).
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.