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 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
szFishis 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,szFishwill 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
;) andCallFuncwill be able to read the raw string.