Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the impact of wrapping an initializer list inside parenthesis?

What is the impact of wrapping an initializer list inside parenthesis? Is it simply another form for list initialization or does it only work in certain scenarios?

For example, consider a:

struct A {
    A(float a, float b) {}
};

int main()
{
    A b(1.0f, 0.0f); // Direct initalization, finds ctor for (float, float)
    A c{1.0f, 0.0f}; // List initalization, finds a matching ctor

    A a({1.0f, 0.0f}); // Is this list initalization... which is expanded?
}
like image 811
Raginator Avatar asked Sep 19 '17 19:09

Raginator


1 Answers

A a(something) says construct a from something. So if we substitute something with {1.0f, 0.0f} then we need to find a constructor where the parmeter can be initialized with {1.0f, 0.0f}. The only constructors we have are the default copy and move constructors that takes a const A& and A&& respectively.

So, doing

A a({1.0f, 0.0f});

Will actually create a temporary A and then use that temporary to initialize a. In this case it will use the move constructor since the object is movable and move constructors are preferred to copy constructors when dealing with rvalues.

like image 88
NathanOliver Avatar answered Dec 20 '22 16:12

NathanOliver