Good advice from the designer of the new std::optional<T>
on how to design modern C++ classes to follow GotW #1's advice to avoid writing initializer_list
constructors that force callers to resort to ()
instead of {}
to disambiguate.
Intuitive Interface -- Part I
by Andrzej Krzemieński
From the article:
Let’s start with the popular C++(11) “uniform initialization” gotcha. Changing braces to parentheses in object initialization may change the semantics of the initialization:
std::vector<int> v1{5, 6}; // 2 elems: {5, 6} std::vector<int> v2(5, 6); // 5 elems: {6, 6, 6, 6, 6}For instance, it is described in Problem 1 of the newly revisited “Guru of The Week” series by Herb Sutter.
When seeing such an example, one might conclude that the new rules for object initialization are very confusing or error-prone. But to me it looks like the problem here lies in how class template
std::vector
has been defined in C++03...
Add a Comment
Comments are closed.