TICS Coding Standard Viewer 
TIOBE Software Quality Framework
Print-friendly version
©TIOBE Software www.tiobe.com
C++ Coding Standard

Rule:  OAL#011Checked automatically with code checker

Synopsis:Use smart pointers for memory management
Severity Level:2
Category:Object Allocation


Smart pointers are pointers that free their allocated memory automatically when they go out of scope. In this way, memory leaks are avoided automatically. Use make_shared and make_unique to create smart pointers.

Example (wrong):

void m() {
  MyObject* ptr = new MyObject(); 
  ptr->DoSomething(); // Use the object in some way
  delete ptr; // Destroy the object. Done with it.

Example (wrong):

void m() {
  std::unique_ptr<MyObject> ptr(new MyObject());

Example (correct):

void m() {
  auto ptr = std::make_unique<MyObject>();

An exception to this rule might seem the use of "reset":

sptr.reset(new Foo);

However, it is better to use:

sptr = std::make_shared();

instead in such a case because it will free the memory of the previous contents and move the new pointer into the smart pointer. In this way, the keywords "new" and "delete" can be banned completely.