Caveat: I stand by this answer since I think it presents a best practice which will improve ~95% of C++ code – probably even more. That said, please read the full comments for a discussion of some important caveats.
Since it was my comment, here’s my presentation explaining this.
In a nutshell:
[Raw] pointers
must. not. own.
resources.
It’s error-prone and unnecessary because we have better ways of managing resources which result in less errors, shorter, more readable code and higher confidence in the correctness of the code. In economic terms: they cost less.
To be more specific with regards to the comment I made:
As of C++11 (out now for two years and implemented, in the relevant parts, by all modern compilers), manually deleting memory is completely unnecessary (unless you write very low-level memory handling code) because you can always use smart pointers instead, and usually don’t even need them (see the presentation). However, C++11 still requires you to use new
when instantiating a new std::unique_ptr
. In C++14, the function std::make_unique
makes this usage of new
unnecessary. Consequently, it’s not needed any more either.
There is still arguably a place for placement-new
in code, but this is (a) an entirely different case from normal new
, even though the syntax is similar, and (b) can be replaced in most cases by using the allocator::construct
function.
James has pointed out an exception to this rule which I had honestly forgotten about: when an object manages its own life-time. I’ll go out on a limb and say that this is not a common idiom in most scenarios, because object life-time can always be managed externally. However, in certain applications it may be beneficial to decouple the object from the rest of the code and let it manage itself. In that case, you need to dynamically allocate the object and deallocate it using delete this
.