What is the effect of wrapping the initializer list inside parentheses?

What is the effect of wrapping the initializer list inside parentheses? Is this just another form for initializing a list, 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? } 
+8
c ++ c ++ 11 brace-initialization
source share
1 answer

A a(something) says the construction of a from something . Therefore, if we substitute something into {1.0f, 0.0f} , we need to find a constructor in which the parameter can be initialized using {1.0f, 0.0f} . The only constructors we have are the default copy and move constructors, which take the values const A& and A&& respectively.

So doing

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

It will actually create a temporary a , and then use that temporary value to initialize a . In this case, he will use the move constructor, since the object is movable, and it is preferable to copy the move constructors when working with r values.

+10
source share

All Articles