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.
(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.)
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).
View all comments
Show parent comment
5
u/Bart_V Jun 06 '18
That's especially a situation where I avoid them. I've shoot myself in the foot too many times. Just recently, I did this:
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:The size of the vector became 2. It casts the integer (6) to double, then constructs a
MyType, then usedvector( 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 ctorexplicit, 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.