Given the new toolset provided by c++ lots of programmers, aiming at code simplification, expressiveness, efficiency, skim through their old code and make tweaks (some point
For-each syntax:
std::vector<int> container;
for (auto const & i : container)
std::cout << i << std::endl;
This blog post proposes the Rule of Zero if all ownerships into a class follow the RAII principle, allowing to get rid of the Rule of Three/Four/Five in C++11.
However, Scott Meyers shows here that not writing explicitly the destructor, copy/move constructors and assignment operators can induce subtle problems if you slightly change your code (say, for debugging). He then recommends to explicitly declare default (C++11 feature) these functions:
~MyClass() = default;
MyClass( const MyClass& ) = default;
MyClass( MyClass&& ) = default;
MyClass& operator=( const MyClass& ) = default;
MyClass& operator=( MyClass&& ) = default;
Use the uniform initialization syntax for variable initialization
widget w(x); // old
widget w{x}; // new
to avoid problems like c++'s most vexing parse (the rest of the reasons why the new way is superior are explained in the linked article by Herb Sutter)
Feature: std::move
"Express clear difference between the copying and moving the resources"
std::string tmp("move");
std::vector<std::string> v;
v.push_back(std::move(tmp));
//At this point tmp still be the valid object but in unspecified state as
// its resources has been moved and now stored in vector container.
Use of override keyword
Mark virtual functions in derived classes as override (if they indeed override of course). This can protect against introducing bugs in the future, e.g. by changing the signature of a virtual function in a base class and forgetting to change the signature in all derived classes accordingly.
Use smart pointers. Notice that there are still good reason to have naked pointers in some cases, the best way to check if a pointer should be smart is to look for the uses of delete
on it.
There should be no reason to use new
either. Replace every new
with make_shared
or make_unique
.
Unfortunately make_unique
didn't make it in the C++11 standard, the best solution IMO is to implement it yourself(see previous link), and put some macros to check for the __cplusplus
version (make_unique
is available in C++14).
Using make_unique
and make_shared
is really important in order to make your code exception safe.