如果我这样声明一个对象:
void main()
{
myclass objectA(anotherclass(true,true,0));
}
即我通过直接调用后者的构造函数来创建一个对象A和另一个对象“另一个类”,“另一个类”的作用域是什么?
它是否仅在 main() 完成时才被销毁?
最佳答案
临时对象在包含它的完整表达式结束时被破坏,即当调用 myclass
的构造函数返回时。
根据 C++11 标准的第 12.2/3 段:
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.
由于这个原因,如果 myclass
的构造函数通过 reference 接受类型为 anotherClass
的参数(const 的左值引用
或右值引用),它不应存储它以供将来使用,因为如果传递临时值,它将悬空,取消引用将是未定义的行为。
只有 objectA
超出范围并在从 main()
函数返回时被销毁。
关于c++ - 括号内声明对象的范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15580903/