Reputation: 1635
I've heard I can initialize a value using this syntax:
int foo = {5};
Also, I can do the same thing using even less code:
int foo{5};
Well, are there any advantages/disadvantages of using them? Is it a good practice, or maybe it's better to use standard: ?
int foo = 5;
Upvotes: 1
Views: 185
Reputation: 70556
The three examples you gave, are not quite the same. Uniform initialization (the ones with { }
) does not allow narrowing conversions
int i = 5.0; // Fine, stores 5
int i{5.0}; // Won't compile!
int i = {5.0}; // Won't compile!
Furthermore, copy initializations (the ones with an =
) do not allow explicit constructors.
The new C++11 feature uniform initialization and its cousin initializer-lists (which generalizes the brace initialization syntax to e.g. the standard containers) is a tricky animal with many quirks. The most vexing parse mentioned in the comments by @Praetorian is only one of them, tuples and multidimensional arrays are another pandora's box.
Upvotes: 5