From 6d21a04e7983f8a2406e5e2fe0b864c7b32ec7d2 Mon Sep 17 00:00:00 2001 From: Jason Turner Date: Mon, 8 Jun 2015 10:23:12 -0600 Subject: [PATCH] Add note on array usage. Closes #15 --- 04-Considering_Safety.md | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/04-Considering_Safety.md b/04-Considering_Safety.md index 2eb760c..0619739 100644 --- a/04-Considering_Safety.md +++ b/04-Considering_Safety.md @@ -56,11 +56,23 @@ delete myobj; // Good Idea -std::shared_ptr myobj = make_shared(); +auto myobj = std::make_unique(); // C++14 +auto myobj = std::unique_ptr(new MyClass()); // C++11 + +// or for reference counted objects + +auto myobj = std::make_shared(); + // ... // myobj is automatically freed for you whenever it is no longer used. ``` +## Use `std::array` or `std::vector` Instead of C-style Arrays + +Both of these guarantee contiguous memory layout of objects and can (and should) completely replace your usage of C-style arrays for many of the reasons listed for not using bare pointers. + +Also, [avoid](http://stackoverflow.com/questions/3266443/can-you-use-a-shared-ptr-for-raii-of-c-style-arrays) 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.