O'Reilly logo

Safe C++ by Vladimir Kushnir

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Chapter 17. Conclusion

Now that we’ve reached the end of this book, let’s go back and summarize the guidelines and strategies we’ve discussed. The first guideline is that we want to diagnose as many errors at compile time as possible. All the other errors will be diagnosed at runtime, and most of the strategies in this book concentrate on catching these errors.

When catching errors at runtime, we are trying to achieve two contrasting goals:

  • Testing as many sanity checks as possible.

  • Having our code run as fast as possible in production.

This can be achieved by making some of the sanity checks temporary. To do this, you need to enable your checks to be switched on and off at compile time and activate them for testing only.

Here is a summary of all the rules formulated in this book.

For diagnosing errors at compile time (Chapter 2):

  • Prohibit implicit type conversions: declare constructors taking one parameter with the explicit keyword and avoid conversion operators.

  • Use different classes for different data types.

  • Do not use enums to create int constants; use them to create new types.

To avoid an “index out of bounds” error (Chapter 4):

  • Do not use static or dynamically allocated arrays; use a template array or vector instead.

  • Do not use brackets on the new and delete operators; leave allocation of multiple elements to the template vector.

  • Use scpp:vector instead of std::vector, and scpp::array instead of a static array. Switch the sanity checks on.

  • For a two-dimensional array, use the scpp::matrix ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required