2025-01-25

Little Surprises #9: too helpful edition

In Qt5, this #include <QString> #include <algorithm> #include <vector> int main() { std::vector<int> v{0, 1, 1, 2, 3, 5, 8}; QString qs("target"); // Search the vector for the string std::find(v.begin(), v.end(), qs); } will build (compile and link). There are very few circumstances where you mean what it will actually do (in this case it's a very expensive no-op), but it is valid code.

This works because of a chain of "helpful" features:

  • You can construct a QChar from an int: QChar(int rc) noexcept
  • .
  • There is a equality test between QChar and QString: bool operator==(QChar lhs, const QString &rhs) noexcept
  • .
  • The find template uses operator== between the contents of the vector and the target.

Each of the behaviors is desireable in isolation, so we don't want to remove any of these options entirely. What causes the surprise is the implicit nature of the type conversion.1 Core guidelines C46 and C164 discuss the uses of explicit annotation to prevent this kind of thing.

BTW: the above code will not compile in QT6 which is a small but significant improvement.


1 Shout out to all the strong typing fans out there.

2025-01-21

When I grow up I want to be...

... organized, detail-oriented, and thorough.

I imagine that will be happening ::checks watch:: any day now. Right? Right?!?

2025-01-11

Dates are important

If you're putting a technical article on the web please, please make sure it has an easy to find date of production assocaiated with it. Seriously, technical stuff changes and sometimes changes fast. I need to know if your advice is a few years old because that might be enough to make it comprehensively wrong.

That is all.