Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++0x uniform initialization "oddity"

Like many, I am pretty excited about C++0x. I try to learn and use the new features in new projects so I can write the best, most easy-to-maintain code possible.

Needless to say, I love the idea behind the new initializers. So I'm looking at them, and these make sense to me:

T x = { 1, 2, 3 }; // like a struct or native array
T x({1, 2, 3});    // copy construct something like an "object literal" in other languages... cool!
return {1, 2, 3};  // similar to above, but returning it, even cooler!

What doesn't make sense to me is this:

T x{1, 2, 3};

It just feels... weird. I'm not sure what syntax that people want to use that this is mimicking, it just doesn't seem "right".

What's the design/thought behind this syntax?

The only example where it seems like it makes a difference is something like this:

std::vector<int> the_vec{4};

which would call the initializer list constructor, but why not just write this then:

std::vector<int> the_vec = {4};

And do what everyone is already comfortable with?

like image 923
Evan Teran Avatar asked Aug 11 '11 19:08

Evan Teran


1 Answers

What's the design/thought behind this syntax?

For one thing, the brace syntax make it possible to avoid vexing parses:

T x(); // function declaration
T x{}; // value-initialized object of type 'T' named 'x'

In C++03, the closest you can get to this is T x((T())); or T x = T();, both of which require T to have an accessible copy constructor.

like image 129
James McNellis Avatar answered Sep 18 '22 09:09

James McNellis