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.
std::shared_ptr<int> p1(new int(42));
std::shared_ptr<int> p2(p1);
std::weak_ptr<int> w1 = p1;
std::unique_ptr<int> u1(new int(42));

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.

auto p1 = std::make_shared<int>(42);

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

auto u1 = std::make_unique<int>(42);

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.

Leave a Comment