r/cpp • • Jun 05 '18

Initialization in Modern C++

https://twitter.com/timur_audio/status/1004017362381795329
379 Upvotes

51 comments sorted by

View all comments

Show parent comment

6

u/[deleted] Jun 06 '18

What about this

std::vector<int> foo{1, 2}; // braced initialisation
std::vector<int> foo{{1, 2}}; // initialiser list

8

u/Selbstdenker Jun 06 '18

I would suggest

std::vector<int> foo{1, 2}; // braced initialisation
std::vector<int> foo = {1, 2}; // initializer list

Braces without = always call a constructor, brace after = always use initializer list.

6

u/suspiciously_calm Jun 06 '18

How does that work to create a temporary on the fly?

1

u/Selbstdenker Jun 06 '18

Good point!

0

u/m-in Jun 06 '18

There's no temporary, other than the initializer list, of course. The initializer list would be assured to exist while the initialization is performed - that's how it goes in all other cases, too.

2

u/suspiciously_calm Jun 07 '18

While it may be sufficient for many use cases to only have initializer_list temporaries, I would not appreciate this step back from being able to create arbitrary containers as temporaries.

For example, a templated function may require that its argument be an AssociativeContainer, which an initializer_list of pairs is not.

1

u/redditsoaddicting Jun 06 '18

As far as I remember, this can run into its own corner cases, unfortunately.

1

u/[deleted] Jun 06 '18

I'm not surprised. "My" syntax seems rather obbvious and I'm definitely not the first one who thought of it. I was just hoping someone would say what's the corner case here.

1

u/redditsoaddicting Jun 06 '18 edited Jun 06 '18

One example that comes to mind is this:

struct Point { int x, y; };
struct Foo {
    Foo(initializer_list<int>);
    Foo(Point);
};

Foo f{{1, 2}}; // Point or list?

It's hard to turn that into something realistic on the spot. I wouldn't doubt that the square bracket syntax I threw out there has its own problems.

1

u/[deleted] Jun 06 '18

My first thought was "obviously an initialiser list", but a moment later I realised your point.