内部声明对象的范围 [英] Scope of an inside-parenthesis declared object

查看:118
本文介绍了内部声明对象的范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

If I declare an object like this:

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

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

i.e. I create an objectA and another object "anotherclass" by directly calling the latter's constructor, what is "anotherclass"'s scope?

完成?

推荐答案

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

The temporary gets destructed at the end of the full expression that contains it, i.e. when the call to the constructor of myclass returns.

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

Per Paragraph 12.2/3 of the C++11 Standard:

临时对象作为最后一步被销毁
在计算表达式(1.9)创建
。这是真的
即使该评估结束时抛出异常。销毁
a临时对象的值计算和副作用仅与完全表达式相关联,而不与任何特定的子表达式相关。

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 的构造函数通过引用接受类型 anotherClass em>(对于 const 或右值引用的左值引用),它不会将其存储以备将来使用,因为如果临时通过,它将悬挂,是未定义的行为。

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.

只有 objectA 超出范围, c $ c> main()函数。

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

这篇关于内部声明对象的范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆