I'm reading A Tour of C++ by Bjarne Stroustrup to brush up on my C++.
In Chapter 1, section 1.8, Stroustrup writes:
The most common case is testing a variable against 0 (or the nullptr). To do that, simply leave out the explicit mention of the condition. For example:
void do_something(vector<int>& v)
{
if (auto n = v.size()) {
// ... we get here if n!=0 ...
}
// ...
}
In my own code, I always try to be explicit, and to accurately convey my intention. I believe that this is considered a general programming best practice.
I consider writing elaborate expressions that evaluate to logical true or false (rather than to 0 or nullptr) as part of this approach. It can also help to avoid subtle implicit casting bugs. In fact, I would think that modern C++ allowed this kind of implicit conversion only for backward compatibility purposes, and would actually expect it to be discouraged in new code.
At the same time, I believe that in his book, Stroustrup suggests best practices that are generally accepted by the community.
My questions are:
- Is this style of implicit conversion really considered a best practice in the C++ development community?
There is no such thing as "the C++ development community", and developers do not unanimously agree to one canonical set of best practices.
That said yes, implicit conversion to bool really is conventionally used in if statements. And there undoubtedly are some who prefer not to rely on it.
- If so, doesn't it contradict other best practices and the general underlying goals of strong typing?
Depends on what those other best practices and general underlying goals try to achieve. Given the wide ranging diversity of opinions, it is quite possible for one best practice to contradict another.
In general, C++ has many implicit conversions between types, and programmers can even have user defined conversions for classes. The fact that the language has implicit conversions implies that there are at least some who consider that implicit conversions are acceptable.
Opinions on which implicit conversions are OK (and in which contexts) differ. Usually, the arguments boil down to how the program could be misinterpreted, and how much a redundantly explicit conversion would unnecessarily draw attention away from the relevant and important parts of the code.
Implicit conversions are just one choice in balancing the dimensions of verbosity versus terseness and explicit versus implicit.
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