简体   繁体   中英

Why does using curley braces when creating an object, calls 2 constructor if one constructor have initializer list

I happen to come across this , and I don't get it, why Foo c{a} called the 2 constructors. I know that every time an object is created, the constructor, is called, so why does it called the foo(std::initializer_list<Foo>) even if he did not do this Foo c{{a}} or Foo c({a}) ?

 struct Foo { Foo() {} Foo(std::initializer_list<Foo>) { std::cout << "initializer list" << std::endl; } Foo(const Foo&) { std::cout << "copy ctor" << std::endl; } }; int main() { Foo a; Foo b(a); // copy ctor Foo c{a}; // copy ctor (init. list element) + initializer list!!! }

If we look at https://en.cppreference.com/w/cpp/language/direct_initialization

Here we see:

T object { arg }; (2) (since C++11)

  1. initialization of an object of non-class type with a single brace-enclosed initializer ( note: for class types and other uses of braced-init-list, see list-initialization )

In https://en.cppreference.com/w/cpp/language/list_initialization there is following bullet:

If T is an aggregate class and the initializer list has a single element of the same or derived type (possibly cv-qualified), the object is initialized from that element (by copy-initialization for copy-list-initialization, or by direct-initialization for direct-list-initialization). (since C++14)

And returning to direct initialization:

the constructors of T are examined and the best match is selected by overload resolution. The constructor is then called to initialize the object.

So, it seems that in this situation clang is right to call copy constructor and GCC is wrong. At least since C++14.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM