Search code examples
c++c++11uniform-initialization

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?


Solution

  • 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.