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

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.

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

1

u/Bart_V Jun 06 '18

Maybe because of brace elision?

I don't know, seems like it only applies when using double braces?

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

Yes indeed. So adding explicit should result in a compiler error since it can't do an implicit construction, not a differently sized vector.

6

u/kwan_e Jun 06 '18

Adding explicit means the implicit conversion for MyType is not available, but the vector still has the size, fill constructor.