Friday, August 3, 2012

C++11 is unsafe

With all due respect for Mr. Sutter, his claim that C++11 is "as clean and safe as any other modern language, and still the king of fast", is simply false. Clean and fast are up to the particular developer and benchmark but safe is more objective, and C++11 is not safe.

  1. It is important for C++ to maintain backwards compatibility with previous versions, so C++11 supports C++03. C++03 is not safe. So, by definition, C++11 is also not safe. For those who are new to the term, safety generally comes down to how bad my program can screw up. Even a wrong Java application will not segfault the VM. C++11 adds some tools to make causing this behavior harder, but it is by no means impossible. C++11 still has pointers. It still has pointer arithmetic.
  2. "But", you say, "we are talking about just the features C++11 added to the language". Still false. Take std::array, which was added in C++11. This code is unsafe: std::array<int 1> arr; arr[2] = 1;. And consider a lambda that captures a reference to a variable that goes out of scope. Perfectly valid C++11. Perfectly unsafe.
  3. Threading in C++11 also allows you to do unsafe things. Just try modifying two non-atomic variables concurrently. You have no guarantees of what will happen.
  4. "BUT", you yell, "he said 'modern language' so...." Indeed, so? I'm not sure what Herb Sutter considers a modern language but let's just take some languages that are somewhat popular today:
    • Java, C# - Considered safe.
    • Clojure, Scala - On the JVM, so one would consider them safe.
    • Python, Ruby, Perl - These are all considered safe languages. You cannot, without effort, access memory you should not.
    • Ada - Hah!
    • F# - Runs on .Net, safe.
    • Ocaml, Haskell - The languages themselves are considered safe but you can do whatever you want if you drop down to C.
    So which languages, exactly, is Mr. Sutter referring to when he says C++11 is as safe as any modern language? I have no idea.

The problem, though, is that it's OK to be honest about C++'s lack of safety. That is the compromise I am agreeing to when I use C++. I want the benefits of it and I understand that I am making a sacrifice. I don't want to be told C++ is something that it is not. This "C++11 is safe" talk is nonsense and not a reflection of reality.

You can follow the discussion on reddit: http://www.reddit.com/r/programming/comments/xml97/c11_is_unsafe/