c++ - 括号内声明对象的范围

标签 c++ scope

如果我这样声明一个对象:

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/

相关文章:

c++ - cudaMallocPitch 和 cudaMemcpy2D

用于构建未知类实例列表的 C++ 模板

c++ - [[noreturn]] 函数如何具有返回类型?

javascript - JavaScript闭包如何工作?

C# lambda 表达式,作用域变量值

c++ - 在笛卡尔平面上旋转 X、Y 坐标的问题

c++ - 像复制一样在STL中转换数组

debugging - Fortran 是否通过子程序多次调用修改输入参数?

actionscript-3 - ActionScript 3.0 : Scope

c++ - 类模板特化的问题