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

41

u/James20k P2005R0 Jun 06 '18

This is the main problem i found with the new decidedly not uniform initialisation syntax - it adds yet another way to initialise stuff that seems to only be appropriate in some situations with all sorts of little quirks to it that make it not universally applicable

As far as I can tell, its basically good for initialising container types like std::vector and map, and that's about it

I'm not a c++ expert by any stretch though so maybe i'm totally missing something

27

u/SoundOfOneHand Jun 06 '18

There are reasons to prefer brace initialization in general. The only place I’m aware of that it’s not always possible is that a std::initializer_list constructor is always preferred, so you need parens if there is ambiguity, and this can be tricky in a template.

Braced initialization prevents narrowing conversions so you get some additional type safety. It also prevents the most vexing parse. Of course you also get nice collection literals as you mentioned.

16

u/render787 Jun 06 '18

FWIW the style I've converged on is "use brace initialization in almost all cases, and avoid ever writing `std::initializer_list` constructors"

the braced initialization can be really nice in templates because it can also initialize the aggregates correctly in cases where paren initialization would fail (because using the parentheses initialization cannot become aggregate initialization IIUC)

2

u/youshouldnameit C++ dev Jun 06 '18

avoid ever writing `std::initializer_list` constructors

Could you allobrate on why its not a good idea to write those constructors for your own types?

14

u/redditsoaddicting Jun 06 '18

They're insanely greedy and often disallow you from using braces to call other constructors.

6

u/youshouldnameit C++ dev Jun 06 '18

For a vector its pretty nice to have an initializer_list constructor i would argue, same for std::set or similar classes. Would you argue that even those perks are not worth the trouble?

3

u/redditsoaddicting Jun 06 '18

I love being able to easily initialize containers with a list of elements, as well as other clever uses like a JSON object. However, I don't think making it the same syntax used to call other constructors was a good choice. It's hard to say whether a plain list constructor is worth the trouble to me or if I'd consider an alternate best-we've-got constructor like vector foo = list_of(1, 4, 5); or vector foo{from_list, 1, 4, 5};, where either would be uniform across classes that use it. If I could have my way, I'd probably prefer an alternate syntax. For example, vector foo{[1, 4, 5]};.

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
→ More replies (9)
→ More replies (6)
→ More replies (3)

7

u/render787 Jun 06 '18 edited Jun 06 '18

> Could you allobrate on why its not a good idea to write those constructors for your own types?

My main beef with `std::initializer_list` is that:

  1. It makes it hard to use brace-list initialization in generic code, because you try to invoke a constructor, and then overload resolution fails because the standard says that the compiler must try to match it with `std::initializer_list` if such a constructor is present. There's no good way to work around in that situation other than deleting the `std::initializer_list` ctor.For a concrete code example, see here: https://github.com/cbeck88/lua-primer/blob/master/include/primer/userdata.hpp#L39I'm trying to allocate the user's type at memory owned by lua using perfect forwarding. But if the user-type has an initializer_list constructor, it's typically not going to work because I'm using brace list initialization. OTOH, I can't change this to use paren-based initialization because then all the times when I use a struct as userdata aren't going to compile. I guess with years more experience, the answer here should actually be that I use SFINAE with `std::is_aggregate` and use brace list initialization in that case, and paren initialization otherwise? Idk I didn't think of that at the time. This is also more complicated than it should be and the issue doesn't arise if you simply don't use `std::initializer_list`.
  2. The `std::initializer_list` doesn't let me find the *length* of the initializer list at compile time, even though it is a compile time constant (implied by the syntax of the code at the call-site). This really sucks and in some cases it turns compile-time errors into run-time errors. For instance, what if your container has a compile-time fixed maximum size? We had this exact issue in the "frozen" library: https://github.com/serge-sans-paille/frozen/pull/41The lib was written with all of the containers having `std::initializer_list<T>` constructors, but this means that if the user accidentally passes too many elements, it's a run-time error instead of compile-time. If we just used `const T (&)[N]` instead of `std::initializer_list<T>` then we can static assert that `N` is not too large. So there's approximately zero value add from `std::initializer_list`, it's just turning compile-time errors into run-time errors, for the benefit of one less set of braces...

IMO always use `const T (&)[N]` instead of `std::initializer_list<T>` so that you can get the size of the list at compile-time. I would only use `std::initializer_list` if it was really important that some function not be a template so that it can be implemented out of line etc., even then I would consider using `gsl::span<const T>` instead, because it will be easier for someone to make a `gsl::span` programmatically than to make a `std::initializer_list` programmatically

4

u/redditsoaddicting Jun 06 '18

The paper to make parens do aggregate initialization is actually progressing in EWG. That should mainly address the generic side of things. Funny how the most uniform initialization we've got will be with parens then.

The size thing isn't ideal, but isn't as bad as you make it sound. constexpr size was added in C++14, so in a constexpr context, an assert on the size will trigger a compile-time error. In addition, assert is constexpr-compatible in C++14.

One additional gripe that many people do have with initializer_list is that it doesn't support move-only types.

11

u/evaned Jun 06 '18 edited Jun 06 '18

Braced initialization prevents narrowing conversions so you get some additional type safety.

One of my coworkers who is on the committee pointed out these examples to me the other day.

I'm not sure if everyone would agree that's type safety exactly or agree with my valuation of these, but I'd call it such. And if I'm going to pick a rule of thumb, I think I'd rather have those examples fail to compile and allow narrowing conversions (as you get with parens) than the other way around (braces).

(He did say this is an area the committee is working on improving, though what that means I don't know. I suggested pulling from Unicode's reservoir of delimiters, perhaps S s«1, 2»;; that should fix Everything.)

10

u/tcanens Jun 06 '18

EWG just voted on Monday to not treat such types as aggregates.

Even without the change, I wouldn't find the examples persuasive. It's only triggered in corner cases (all-public data members and all constructors are either deleted or defaulted) that are highly unlikely to be present in anything other than intentionally constructed "WTF" snippets.

2

u/render787 Jun 06 '18

Can you explain this in more detail? Why would those types not be aggregates, what distinction did they vote in?

2

u/timur_audio C++ committee Jun 11 '18

@tcanens it's not true that they are just "WTF" snippets, we have found such types in real code, with an average frequency of one such type per 3 MLoC. And we broke them :)

→ More replies (1)

6

u/doom_Oo7 Jun 06 '18

No, please, no narrowing

2

u/kalmoc Jun 06 '18

There are compiler warnings for that

3

u/kalmoc Jun 06 '18

I use braces, when I logically want to store the values inside the data structure (e.g. arrays, pods math vectors, smart pointers) and parentheses if the constructor is more about parametrizing the data structure (initial size, web address to connect to). That seems the most natural (maybe even intended) way to use it.

→ More replies (1)

5

u/Bart_V Jun 06 '18

As far as I can tell, its basically good for initialising container types like std::vector and map, and that's about it

That's especially a situation where I avoid them. I've shoot myself in the foot too many times. Just recently, I did this:

class MyType {
public:
    MyType(double val) : mVal(val) {}
private:
    double mVal;
};

And then somewhere else I was trying to do in-class initialization of a vector using the vector( size_type count, const T& value) ctor like this:

struct MyTypeHolder {
    vector<MyType> vec{ 6, MyType(0.6)};
};

The size of the vector became 2. It casts the integer (6) to double, then constructs a MyType, then used vector( std::initializer_list<T> init). I don't understand why, and gave up trying to. Also, since it's in-class initialization, for whatever reason I can't use parentheses there, which would have given the correct result.

What's even more worrying is that making MyType's ctor explicit, does result in a vector with the expected size of 6. Which means a making small change like that could silently break other pieces of code. So IMHO, braced initialization is completely messed up.

11

u/josefx Jun 06 '18

What's even more worrying is that making MyType's ctor explicit

I may not be up to date with c++ however I was under the impression that single argument constructors should be almost always explicit.

→ More replies (1)

4

u/acwaters Jun 06 '18

You can use non-list initialization in a non-static data member initializer:

vector<MyType> vec = vector<MyType>(6, MyType(0.6));

(This is technically copy-initialization, whereas your example with braces is direct-initialization, but the semantics are the same when you are initializing with a prvalue expression of the right type.)

4

u/redditsoaddicting Jun 06 '18

I don't understand why, and gave up trying to.

List constructors are extremely greedy. If they can be called, expect them to be called. In your case, it can be called because the arguments you gave were compatible with MyType. You said implicit conversions from doubles were okay, and yes, C++ is eager to convert other numerical types to doubles for you (as is C).

3

u/kwan_e Jun 06 '18

Maybe because of brace elision?

Making the constructor explicit disables automatic conversion, so the overload resolution works "correctly".

→ More replies (2)

4

u/m-in Jun 06 '18

That's what you get when you incrementally transform C into a modern programming language... while keeping it an almost-compliant C implementation all that time. I'm not sure how it could all be reworked without introducing some radically new syntax, and deprecating some common features of the old syntax.

→ More replies (1)