Tag Archives: new

Farewell to new and delete

C++11 introduced several smart pointers (residing in the <memory> header):

  • std::shared_ptr: retains shared ownership of an object, that is destroyed when the last shared_ptr that holds a reference to it is destroyed or assigned another pointer.
  • std::unique_ptr: retains sole ownership of an object, that is destroyed when the unique_ptr goes out of scope
  • std::weak_ptr: retains a non-owning reference to an object managed by a shared_ptr. It does not participate in the reference counter of the shared pointer. It is mainly use to break circular dependencies.

While these smart pointers manage resources automatically, so there is no need to delete object explicitly, they still require explicit instantiation with new for the managed resource.

C++11 introduced std::make_shared, a free function that constructs an object and wraps it in a std::shared_ptr object.

C++14 introduces another free function, std::make_unique, that constructs an object and wraps it in a std::unique_ptr object.

With these smart pointer and functions available there is no need any more to use new and delete in your C++ code. Besides avoiding explicit allocation and release these functions have another important advantage: they prevent memory leaks that could happen in the context of function calls. You can read Herb Sutter’s GotW #102: Exception-Safe Function Calls for details about this problem.