About the usage of new and delete, and Stroustrup's advice

c++, c++11

Solution

It's a great rule. In fact, you can avoid using `new` in arguments to smart pointers by using the appropriate `make_` functions. For example, instead of:

std::shared_ptr<int> p(new int(5));

You can often do:

auto p = std::make_shared<int>(5);

This also has the benefit of being more exception safe. While a `std::make_unique` doesn't yet exist, it is planned to make its way into C++14 (it is already in the working draft). If you want it now, there are some existing implementations.

You can go a step further and even avoid using `new` and `delete` in constructors and destructors. If you always wrap dynamically allocated objects in smart pointers, even when they're class members, you won't need to manage your own memory at all. See the Rule of Zero. The idea is that it's not the responsibility of your class to implement any form of ownership semantics (SRP) - that's what the smart pointers are for. Then you theoretically never have to write copy/move constructors, copy/move assignment operators or destructors, because the implicitly defined functions will generally do the appropriate thing.

Problem

About the usage of new and delete, and Stroustrup's advice... He says something like (but not exactly, this is from my notes of his book): A rule of thumb is that, `new` belongs in constructors and similar operations, `delete` belongs in destructors. In addition, `new` is often used in arguments to resource handles. Otherwise avoid using `new` and `delete`, use resource handles (smart pointers) instead. I was wondering if the more experienced folks with C++11 have really applied this or not. My impression of this was, wow this seems like a really cool rule to follow. But then I got suspicious, as for any general rule. At the end of the day you will end up using new and delete wherever necessary. But maybe this rule is a good guideline I don't know.

Original source

Related problems