这个字符串的作用域是什么? [英] What's the scope of this string?
问题描述
如果我有以下代码:
{
UnicodeString sFish = LFISH
char * szFish = AnsiString(sFish).c_str();
CallFunc(szFish);
}
然后创建的临时AnsiString的范围是什么是szFish指向有效数据?它仍然对CallFunc函数有效吗?
它的作用域是最后一行还是整个块?
C ++ 11标准$ 12.2.3说:
实现引入一个类的临时对象,
有一个非平凡的构造函数(12.1,12.8),它应该确保为临时对象调用一个
构造函数。类似地,
析构函数将被调用一个具有非平凡
析构函数(12.4)的临时变量。 临时对象被销毁为
中的最后一步,计算full-expression(1.9)(词法)包含创建它们的
点。评估
结束抛出异常。破坏临时对象的值计算和副作用
仅与
full-expression关联,而不与任何特定的子表达式关联。
(强调我)
这里还有其他注意事项,但它们不适用于这种情况。在你的情况下,完整的表达式是这个语句的指示部分:
char * szFish = AnsiString(sFish).c_str ;
// ^^^^^^^^^^^^^^^^^^^^^^^
所以,赋值了 szFish
的瞬间,你的临时对象的析构函数(即 AnsiString(sFish)
)将被调用,其内部存储器表示( c_str()
指向)将被释放。因此, szFish
会立即成为一个悬空指针,任何访问都将失败。
说
CallFunc(AnsiString(sFish).c_str());
,如下所示,临时文件将在 full >表达式(即,在 If I have the following code: 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: When an implementation introduces a temporary object of a class that
has a non-trivial constructor (12.1, 12.8), it shall ensure that a
constructor is called for the temporary object. Similarly, the
destructor shall be called for a temporary with a non-trivial
destructor (12.4). Temporary objects are destroyed as the last step in
evaluating the full-expression (1.9) that (lexically) contains the
point where they were created. This is true even if that evaluation
ends in throwing an exception. The value computations and side effects
of destroying a temporary object are associated only with the
full-expression, not with any specific subexpression. (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 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 这篇关于这个字符串的作用域是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!;
)和 CallFunc
将能够读取原始字符串。 / p> {
UnicodeString sFish = L"FISH";
char *szFish = AnsiString(sFish).c_str();
CallFunc(szFish);
}
char *szFish = AnsiString(sFish).c_str();
// ^^^^^^^^^^^^^^^^^^^^^^^^^
szFish
is assigned, the destructor of your temporary object (i.e. AnsiString(sFish)
) will be called and its internal memory representation (where c_str()
points to) will be released. Thus, szFish
will be immediately become a dangling pointer and any access will fail.CallFunc(AnsiString(sFish).c_str());
;
) and CallFunc
will be able to read the raw string.