Thursday, April 9, 2015

Why does C++ allow unsafe code?

That is, why does C++ support operations that can be used to violate the rules of static (compile-time) type safety?
  • to access hardware directly (e.g. to treat an integer as a pointer to (address of) a device register)
  • to achieve optimal run-time and space performance (e.g. unchecked access to elements of an array and unchecked access to an object through a pointer)
  • to be compatible with C
That said, it is a good idea to avoid unsafe code like the plague whenever you don’t actually need one of those three features:
  • don’t use casts
  • keep C-style [] arrays out of interfaces (hide them in the innards of high-performance functions and classes where they are needed and write the rest of the program using proper strings, vectors, etc.)
  • avoid void* (keep them inside low-level functions and data structures if you really need them and present type safe interfaces, usually templates, to your users)
  • avoid unions
  • if you have any doubts about the validity of a pointer, use a smart pointer instead
  • don’t use “naked” new and delete (use containers, resource handles, etc., instead)
  • don’t use ...-style variadic functions (“printf style”)
  • avoid macros except for #include guards

Almost all C++ code can follow these simple rules. Please don’t be confused by the fact that you cannot follow these rules if you write C code or C-style code in C++.

No comments:

Post a Comment