In the Scott Meyer's book Effective Modern C++ we can read, that:
std::vector<bool> features(const Widget& w);
Widget w;
…
bool highPriority = features(w)[5];
…
processWidget(w, highPriority);
and an option with auto
auto highPriority = features(w)[5];
which causes undefined behavior, because of the fact, that features()
is returning std::vector<bool>
, that uses proxy Object of type std::vector<bool>::reference
when returning a value from opearator[]
.
As a solution to this is adviced not to stop using auto
, but using static_casts
.
So Scott Meyers advice to use:
auto highPriority = static_cast<bool>(features(w)[5]);
instead of:
bool highPriority = features(w)[5];
My question is: What is a real difference between those two? In my opinion both are the same, because both methods make refactoring harder in exactly the same way (changing return value type in the function features does not make variable highPriority a different type) and second one is shorter to write.
If you don't like the interface of features
, you can hide the ugliness in a helper function
bool is_high_priority(const Widget& w)
{ return features(w)[5]; }
and now your
auto highPriority = is_high_priority(w);
works as expected.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With