使用带有clang的初始化器列表初始化简单结构 [英] Initializing simple structs using initializer lists with clang
问题描述
struct E_Point {
double x, y;
E_Point(): x(0), y(0) {}
E_Point(double x, double y) : x(x), y(y) {}
};
E_Point problem[] = {
{0.3871953044519425, -0.91857980824611341}, // Error: initialization of non-aggregate type 'E_Point' with an initializer list
{0.36139704793723609, 0.91605957361605106},
{-0.8208980020500205, 0.52853407296583088},
{0.36178501611208552, 0.88880385168617226},
{-0.43211245441046209, 0.6803420222771047}
};
使用 clang
进行编译3.1。
Compiling with clang
3.1.
我应该指出,这是在GCC 4.6.1上编译的。
I should point out that this compiles on GCC 4.6.1.
我目前的理解是 problem
是一个非聚合类型,因为它是一个结构体数组,使它复合,而不仅仅是一个结构或数组。
My current understanding is that problem
is a non-aggregate type because it is an array of structs, making it compound and not just simply either a struct or array.
但是将 -std = c ++ 11
标志发送到 clang
不缓解问题。
But sending the -std=c++11
flag to clang
does not alleviate the problem.
更新:好的。看起来我的版本 clang
是有点瑕疵,无法处理这种无论什么原因。
Update: Okay. Looks like my version of clang
is somehow flawed and can't handle this for whatever reason.
init是什么更传统的方式?我这样做吗?这个编译,但是它产生相同的代码?它会调用ctor而原来不是?
What's a more traditional way to init? Do I do it this way? This compiles, but does it produce the same code? Will it call the ctor while the original doesn't?
E_Point problem[] = {
E_Point(0.3871953044519425, -0.91857980824611341), // 1559
E_Point(0.36139704793723609, 0.91605957361605106), // 1560
E_Point(-0.8208980020500205, 0.52853407296583088), // 1798
E_Point(0.36178501611208552, 0.88880385168617226), // 1799
E_Point(-0.43211245441046209, 0.6803420222771047) // 1800
};
推荐答案
这是clang ++中的一个错误:
That is a bug in clang++:
http://llvm.org/bugs/ show_bug.cgi?id = 12670
在您的情况下,您可以使用对构造函数的显式调用,就像您在上一个代码片段中提供的。至于语义是否真的相同(将生成相同的代码),在大多数情况下它会。
In your case you can just use the explicit call to the constructor, as you provide in the last code snippet. As of whether the semantics are really the same (will it generate the same code), in most cases it will.
不同的语法会导致不同的行为的情况是,当被构造的类型有一个构造函数,它接受 std :: initializer_list< ;
,在这种情况下,括号初始化器将构造初始化列表。如果类型没有这样的构造函数,你的情况下,括号初始化将调用适当的构造函数。
The case where the different syntax will lead to different behavior is when the type being constructed has a constructor that takes a std::initializer_list<>
, in which case the brace-initializer will construct that initializer list. If the type does not have such a constructor, as is your case, the brace-initializer will call the appropriate constructor.
这篇关于使用带有clang的初始化器列表初始化简单结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!