Considering Safety

    • Temporaries and local values

    references: https://twitter.com/lefticus/status/635943577328095232

    Do not pass and return simple types by const ref

    Instead, pass and return simple types by value. If you plan not to change passed value, declare them as const, but not refs:

    Why? Because passing and returning by reference leads to pointer operations instead by much more faster passing values in processor registers.

    Avoid Raw Memory Access

    Raw memory access, allocation and deallocation, are difficult to get correct in C++ without . C++11 provides tools to avoid these problems.

    Also, avoid using std::shared_ptr to hold an array.

    Use Exceptions

    Exceptions cannot be ignored. Return values, such as using boost::optional, can be ignored and if not checked can cause crashes or memory errors. An exception, on the other hand, can be caught and handled. Potentially all the way up the highest level of the application with a log and automatic restart of the application.

    Stroustrup, the original designer of C++, much better than I ever could.

    Use the C++-style cast (static_cast<>, dynamic_cast<> …) instead of the C-style cast. The C++-style cast allows more compiler checks and is considerably safer.

    But consider refactoring of program logic (for example, additional checking on overflow and underflow) if you need to cast to int. Measure three times and cut 0.9999999999981 times.

    Do not define a variadic function

    Variadic functions can accept a variable number of parameters. The probably best known example is printf(). You have the possibility to define this kind of functions by yourself but this is a possible security risk. The usage of variadic functions is not type safe and the wrong input parameters can cause a program termination with an undefined behavior. This undefined behavior can be exploited to a security problem.
    If you have the possibility to use a compiler that supports C++11, you can use variadic templates instead.

    It is technically possible to make typesafe C-style variadic functions with some compilers

    by David Wheeler is a good analysis of the current state of code safety and how to ensure safe code.