There are two issues with your suggestion.
A False Sense of Security
Your proposal induce a false sense of security. Sure, the standard guarantees that if you call delete
on a null pointer, it won't blow up. However, you have forgotten one tiny fact: there is not a single pointer to your object.
int* p = new int(8);
int* q = p;
delete p; p = 0;
delete q; // Undefined Behavior
Therefore, this practice is useless. And because a false sense of security is worse than no security at all, I actually strongly discourage it. In the hope that people will think before applying delete
nilly-willy.
Which brings us to the second issue
Don't you ever dare using delete
delete
should be reserved to implementers of smart pointers or other containers. The following apply:
- For Expert Only
- (Experts) Don't*
*There's probably an already existing debugged implementation for what you're trying to achieve.
There are heaps of existing tools to manage memory:
- the ubiquitous various flavors of smart pointers:
std::unique_ptr
or std::auto_ptr
(depending on your version of C++), std::scoped_ptr
, std::shared_ptr
(and its comparse std::weak_ptr
, or their boost/tr1 equivalent)
- the ubiquitous various flavors of containers:
boost::array
, boost::scoped_array
, std::vector
(and co)
- and the lesser known, but so useful in OO:
boost::ptr_vector
(and co)
- there's even
boost::intrusive_ptr
and the Boost Intrusive Containers library or the Boost MultiIndex library (with the BiMap derivative)
- and probably several other boost libraries, perhaps more specialized, like Boost.Signals
With such an heterogeneous wildlife, it's hard to think that you suddenly discovered a new way of using data that is so different from what we do that you would need something else. And if you have, feel free to post it, we'll help you understand how to use those tools to fit your situation (or give you pointers on how to create a new form of smart pointer).