8

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? } 

1 Answer 1

10

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Those damn implicit constructors... takes time to get used to. Thanks!
@Raginator No problem. I just updated the answer to also include move semantics as in this case it will use the move constructor instead of the copy constructor as it is a better match.
Although technically correct, no move or copy constructor will be called as they will be elided (even mandatory copy elision in C++17). While in C++14 those constructors must be still accessible, they even can be even deleted in C++17.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.