-
Notifications
You must be signed in to change notification settings - Fork 128
RAII Memory Management
-
Avoid
new/delete
bare pointers: use objects, references to objects, smart pointers:unique_ptr, shared_ptr,
and the standard template library (STL) containers (e.g.std::vector, std::map, std::queue
) when corresponding for automatic memory management. In addition, use smart pointers for polymorphism and/or to allownullptr
as a valid state (e.g. waiting for message). Only use bare pointers as "reference" pointers, not to manage memory manually.-
Don't
double *variable = new double [Nx];
-
Do
std::vector<double> variable(Nx);
-
Don't
-
std::move
and C++11: C++11 adds overloaded standard functions and constructors that automatically identify an object's move constructor (&&
) (e.g. STL containers element insertion, deletion). Only use std::move explicitly when it is not clear if the copy (&
) or move (&&
) constructor will be called (e.g. large user-defined objects moved to a container, in that case prefer emplace_back). -
Use RAII: resource allocation is initialization. Constructors must allocate, while destructors will take care of all object deallocations and system resources (e.g. file, shared memory). Fine tuning memory should be used only if it causes a big impact. STL containers and smart pointers are RAII complaint. If a class only contains RAII members destructors should be empty or declared with the keyword
default
.