Call ctor with brackets

A simple question about C ++ 11 syntax. There is an example code (one source has been reduced)

struct Wanderer { explicit Wanderer(std::vector<std::function<void (float)>> & update_loop) { update_loop.emplace_back([this](float dt) { update(dt); }); } void update(float dt); }; int main() { std::vector<std::function<void (float)>> update_loop; Wanderer wanderer{update_loop}; // why {} ??? } 

I would like to know how a call constructor with curly braces like Wanderer wanderer{update_loop}; can be possible Wanderer wanderer{update_loop}; This is not a list of initializers, nor uniform initialization. What it is?

+6
source share
2 answers

This is not a list of initializers, nor uniform initialization. What it is?

Your premise is incorrect. This is a uniform initialization, and in a standard expression - a parenthesis-bracket-initialization.

If a constructor accepting std::initializer_list is present, using curly braces to construct objects is equivalent to using parentheses.

The advantage of using curly braces is that the syntax is immune to the Most Vexing Parse problem:

 struct Y { }; struct X { X(Y) { } }; // ... X x1(Y()); // MVP: Declares a function called x1 which returns // a value of type X and accepts a function that // takes no argument and returns a value of type Y. X x2{Y()}; // OK, constructs an object of type X called x2 and // provides a default-constructed temporary object // of type Y in input to X constructor. 
+13
source

This is just C ++ 11 syntax. You can initialize the objects that call their constructor with curly braces. You just need to keep in mind that if the type has an initializer_list constructor, this takes precedence.

+1
source

All Articles