从代码中生成的可执行文件由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 initialization:
[...] T( { arg1, arg2, ... } ) (7) [...]
The effects of list initialization of an object of type T are:
If
T
is an aggregate type, aggregate initialization is performed.Otherwise, If the braced-init-list is empty and
T
is a class type with a default constructor, value-initialization is performed.
[...]
我得出结论,Foo({})
应该调用默认构造函数。
哪里有问题?
T
的对象的效果为...”,这样会更清晰吗? - CaseyU({...})
替换T({...})
是个好主意,这样可以避免文本引用T
的问题,而这里是不正确的。 - Johannes Schaub - litb