Monday, October 07, 2013

C++ bollocks

Every now and then I come across what I call "C++ bollocks". What do I mean? I am referring to various statements made about certain aspects of C++ that are, well, complete bollocks. The statements might have been true to some extent in the
dim and distant past, but anyone still trotting out these statements in this day and age is, in my arrogant opinion, talking bollocks. Here are some examples, divided into categories.

all too frequent bollocks

  • C++ iostream are too slow. Use the printf family instead.
    As one person has pointed out via the comments, I do not have a direct refutation for this yet. The FAQ link merely explains why iostreams are generally superior.
  • C++ exceptions are too slow. Use error codes or boolean return status instead.
    see the FAQ. Also see , "Why use exceptions?"
  • Don't use std::endl, it's too slow.
    It is true that std::endl flushes the output buffer, which has a performance hit. This is even mentioned in the FAQ-lite. However, such concerns over micro-efficiency are usually misplaced. Premature optimisation is the root of all evil.
  • C++ strings are too slow. Prefer C char arrays.
    Some people prefer C to C++. Those people should leave C++ alone and work in their preferred language. Also see , "What's wrong with arrays?".
  • avoid virtual functions. The performance hit on virtual dispatch is too great.
    See the FAQ
  • always implement getters and setters as inline. It's faster.
    See the FAQ. As ever, premature optimisation is the root of all evil. People making these claims never have the figures to back them up. Their response to being challenged is "everyone knows this".
  • provide convenient implicit type conversion by implementing cast operators
    Actually you usually want to do the complete opposite of this. This is why many coding guidelines say that single arg ctors must be qualified by explicit. and that cast operators should not be written.
  • Failing to make a base class dtor virtual is no big deal. It will just result in a small memory leak.
    Wrong. It is actually undefined behaviour. See the FAQ and the Jargon file
  • saying delete mem instead of delete []mem (to go with the new type[count]) is no big deal. It will just result in a small memory leak.
    Wrong. It is actually undefined behaviour. See the FAQ and
    of course, the Jargon File
  • Use Yoda notation to guard against accidental assignment. I have a rant about this one.

infrequent bollocks

  • don't throw exceptions from constructors.
    this is from the same school of bollocks as "C++ exceptions are too slow".
    See the FAQ
  • prefer pointers to references since references dont make it clear when the object can be modified.
    See the FAQ and this Parashift article.