gedamial February 2016

C++ Copy constructor gets called instead of initializer_list<>

Based on this code

struct Foo 
{
   Foo() 
   {
       cout << "default ctor" << endl;
   }

   Foo(std::initializer_list<Foo> ilist) 
   {
       cout << "initializer list" << endl;
   }

   Foo(const Foo& copy)
   {
       cout << "copy ctor" << endl;
   }
};

int main()
{

   Foo a;
   Foo b(a); 

   // This calls the copy constructor again! 
   //Shouldn't this call the initializer_list constructor?
   Foo c{b}; 



   _getch();
   return 0;
}

The output is:

default ctor

copy ctor

copy ctor

In the third case, I'm putting b into the brace-initialization which should call the initializer_list<> constructor.

Instead, the copy constructor takes the lead.

Will someone of you tell me how this works and why?

Answers


jaggedSpire February 2016

You're encountering an interesting aspect of list initialization, where if the list fulfills certain requirements it may be treated like a copy-initialization rather than a list-initialization.

from cppreference:

The effects of list initialization of an object of type T are:

If T is a class type 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)

Foo c{b} fulfills all these requirements.

Post Status

Asked in February 2016
Viewed 2,030 times
Voted 8
Answered 1 times

Search




Leave an answer