If I have the following code:
{
UnicodeString sFish = L"FISH";
char *szFish = AnsiString(sFish).c_str();
CallFunc(szFish);
}
Then what is the scope of the temporary AnsiString that's created, and for how long is szFish pointing to valid data? Will it still be valid for the CallFunc function?
Will it's scope last just the one line, or for the whole block?
The scope of AnsiString in this case is "from right before the call to c_str(), until right after." It may help to think of it this way:
The C++11 standard $12.2.3 says:
(emphasis mine)
There are additional caveats to this, but they don't apply in this situation. In your case the full expression is the indicated part of this statement:
So, the instant
szFish
is assigned, the destructor of your temporary object (i.e.AnsiString(sFish)
) will be called and its internal memory representation (wherec_str()
points to) will be released. Thus,szFish
will be immediately become a dangling pointer and any access will fail.You can get around this by saying
instead, as here, the temporary will be destroyed (again) after the full expression (that is, right at the
;
) andCallFunc
will be able to read the raw string.I would replace:
with:
I don't know the
AnsiString
class but in your code its destructor will fire before your call toCallFunc()
, and will most probably release the string you point to with*szFish
. When you replace the temporary object with a "named" object on stack its lifetime will extend until the end of the block it is defined in.szFish
is invalid before the call toCallFunc()
, becauseAnsiString
is a temporary object that is destructed immediately andszFish
is pointing to its internal buffer which will have just been deleted.Ensure that the
AnsiString
instance is valid for the invocation ofCallFunc()
. For example: