Is there a rule of thumb to decide when to use the old syntax ()
instead of the new syntax {}
?
To initialize
I've found the answer in the standard docs(latest draft). Hopefully, I'll try to explain what I understood.
First, if a class defines an initialization list constructor, then it is used whenever suitable:
§ 8.5.4 (page 203)
Initializer-list constructors are favored over other constructors in list-initialization (13.3.1.7).
I think this is a great feature to have, eliminating the headache associated with the non-uniform style :)
Anyway, the only gotcha(which my question is about) is that if you design a class without the initializer constructor, then you add it later you may get surprising result.
Basically, imagine std::vector
didn't have the initializer list constructor, then the following would create a vector with 10 elements:
std::vector numbers{10};
By adding the initializer list constructor, the compiler would favor it over the other constructor because of the {}
syntax. This behavior would happen because the elements of the init-list {10}
are accepted using the init-list constructor. If there is no acceptable conversion, any other constructor shall be used e.g.:
std::vector vec{10};
// a vector of 10 elements.
// the usual constructor got used because "{0}"
// is not accepted as an init-list of type string.