clang 3.5.0 和 gcc 4.9.1 从代码中生成的可执行文件
#include <iostream>
struct Foo
{
Foo() { std::cout << "Foo()" << std::endl; }
Foo(int x) { std::cout << "Foo(int = " << x << ")" << std::endl; }
Foo(int x, int y) { std::cout << "Foo(int = " << x << ", int = " << y << ")" << std::endl; }
};
int main() // Output
{ // ---------------------
auto a = Foo(); // Foo()
auto b = Foo(1); // Foo(int = 1)
auto c = Foo(2, 3); // Foo(int = 2, int = 3)
auto d = Foo{}; // Foo()
auto e = Foo{1}; // Foo(int = 1)
auto f = Foo{2, 3}; // Foo(int = 2, int = 3)
auto g = Foo({}); // Foo(int = 0) <<< Why?
auto h = Foo({1}); // Foo(int = 1)
auto i = Foo({2, 3}); // Foo(int = 2, int = 3)
}
表现如评论。
来自cppreference:cpp/language/list 初始化:
[...] T( { arg1, arg2, ... } ) (7) [...]
T 类型对象的列表初始化的效果是:
如果
T
是聚合类型,则执行聚合初始化。否则,如果括号初始化列表为空并且
T
是具有默认构造函数的类类型,则执行值初始化。[...]
我的结论是Foo({})
应该调用默认构造函数。
错误在哪里?