2

如果我声明这样的对象:

void main()
{
    myclass objectA(anotherclass(true,true,0));
}

即我通过直接调用后者的构造函数来创建一个objectA和另一个对象“anotherclass”,“anotherclass”的范围是什么?

只有当 main() 完成时它才会被破坏?

4

2 回答 2

4

临时在包含它的完整表达式的末尾被破坏,即当对构造函数的调用myclass返回时。

根据 C++11 标准的第 12.2/3 段:

临时对象被销毁作为评估完整表达式(1.9)的最后一步,该表达式(词法上)包含它们被创建的点。即使评估以抛出异常结束也是如此。销毁临时对象的值计算和副作用仅与完整表达式相关联,与任何特定子表达式无关。

For this reason, if myclass's constructor takes an argument of type anotherClass by reference (either lvalue reference to const or rvalue reference), it shall not store it for future use, because it will be dangling if a temporary is passed, and dereferencing it would be Undefined Behavior.

It is only objectA that goes out of scope and gets destroyed when returning from the main() function.

于 2013-03-22T22:34:18.017 回答
2

anotherclass对象没有范围。范围是名称的属性,而不是对象的属性,并且该对象没有命名。它只是一个临时对象,将在完整表达式结束时被销毁。

这是范围的定义(§3.3.1):

通常,每个特定名称仅在程序文本的某个可能不连续的部分(称为其范围)内有效。

于 2013-03-22T22:34:04.440 回答