当一个数组由一个子表达式创建时,其中的临时表会发生什么? [英] When an array is created by a subexpression, what happens with the temporaries therein?

查看:120
本文介绍了当一个数组由一个子表达式创建时,其中的临时表会发生什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读FDIS的这两个段落(12.2p {4,5}):

I was reading these two paragraphs of the FDIS (12.2p{4,5}):


临时在与完全表达式的结束不同的点被销毁。第一个上下文是当调用默认构造函数来初始化数组的元素时。如果构造函数具有一个或多个默认参数,则在构造下一个数组元素(如果有)之前,对在默认参数中创建的每个临时变量进行销毁。

There are two contexts in which temporaries are destroyed at a different point than the end of the full-expression. The first context is when a default constructor is called to initialize an element of an array. If the constructor has one or more default arguments, the destruction of every temporary created in a default argument is sequenced before the construction of the next array element, if any.


第二个上下文是当引用绑定到临时时。引用绑定到的临时对象或作为引用绑定到的子对象的完整对象的临时对象在引用的生命周期内仍然存在,除了:
[...]

The second context is when a reference is bound to a temporary. The temporary to which the reference is bound or the temporary that is the complete object of a subobject to which the reference is bound persists for the lifetime of the reference except: [...]


  • 在函数调用(5.2.2)中,引用参数的临时绑定将持续到包含调用的完整表达式完成。

这两个似乎与以下情况矛盾

These two two seem to contradict for the following case

struct A {
  A() { std::cout << "C" << std::endl; }
  ~A() { std::cout << "D" << std::endl; }
};

struct B {
  B(A const& a = A()) { }
};

typedef B array[2];

int main() {
  array{};
}

将输出 CDCD 根据第一个上下文的需要,或者将输出 CCDD 根据第二个上下文的需要? GCC似乎遵循第二个上下文描述并输出 CCDD 。我忽略了一些重要的事情吗?

Will this output CDCD as required by the first context, or will this output CCDD as required by the second context? GCC seems to follow the second context description and outputs CCDD. Have I overlooked something important?

编辑:我不认为它需要C ++ 0x。这个 new - 表达式也受我的问题影响:

I don't think it needs C++0x. This new-expression is affected too by my question:

new array(); /* CDCD or CCDD ?? */

在这种情况下,GCC遵循第一个上下文,并输出 CDCD

In this case though, GCC follows the first context, and outputs CDCD.

推荐答案

我不认为有矛盾。

5.2.2清楚地说明了函数调用是什么。函数调用是后缀表达式后跟括号
包含可能为空的
逗号分隔的表达式列表
,它们构成
函数的参数。

5.2.2 clearly says what a function call is. A function call is a postfix expression followed by parentheses containing a possibly empty, comma-separated list of expressions which constitute the arguments to the function.

在程序中的任何地方似乎没有调用 B :: B(A const&)的函数,所以我没有看到第二个段落是如何应用的。

There doesn't seem to be a function call to B::B(A const&) anywhere in your program, so I don't see how the second passage applies.

这篇关于当一个数组由一个子表达式创建时,其中的临时表会发生什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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