std :: initializer_list和元素的求值顺序 [英] std::initializer_list and order of evaluation of the elements
问题描述
逗号(,
)是 std :: initializer_list
吗?
例如:是这个UB:
#include <vector>
int main()
{
auto nums = []
{
static unsigned x = 2;
return ( x++ % 2 ) + 1;
};
std::vector< int > v{ nums(), nums(), nums(), nums(), nums() };
// not sure if this is different: (note the additional brackets)
// std::vector< int > v({ nums(), nums(), nums(), nums(), nums() });
for( auto i : v )
{
std::cout << i;
}
return 0;
}
推荐答案
根据C ++ 11第8.5.4节[dcl.init.list]第4段:
According to C++11 § 8.5.4 [dcl.init.list] paragraph 4:
4在braced-init-list的initializer-
initializer-clause,包括从包展开
(14.5.3)的任何结果,按它们出现的顺序被评估。也就是说,
每个值计算和与给定的
initializer子句相关联的副作用在每个值计算之前被排序,并且
副作用与在$ b $中的任何初始化子句相关联b初始化列表的逗号分隔列表。
4 Within the initializer-list of a braced-init-list, the initializer-clauses, including any that result from pack expansions (14.5.3), are evaluated in the order in which they appear. That is, every value computation and side effect associated with a given initializer-clause is sequenced before every value computation and side effect associated with any initializer-clause that follows it in the comma-separated list of the initializer-list.
据我所知,GCC 4.8.1有一个相对于评估的错误的初始化器。我在这里描述它
As far as I know GCC 4.8.1 has a bug relative to evaluation of initializers. I described it here
http://cpp.forum24.ru/?1-3-0-00000063-000-0-0-1378892425
尽管文本是用Russion编写的,但是可以使用例如google translate来简单地翻译成英语。
Though the text is written in Russion but it can be simply translated in English by using for example google translate.
这篇关于std :: initializer_list和元素的求值顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!