This isn't a good idea. Macros are not the proper tool for the job. Aside from the fact that it probably isn't possible, it will be confusing to anyone maintaining your code. There are several superior alternatives.
If you have C++11, you should prefer to use smart pointers such as std::unique_ptr
and std::shared_ptr
whenever possible. MatthiasB also makes a valid point that you should opt to take advantage of the standard library and use std::vector
instead of dynamically allocated arrays.
Otherwise, you can take advantage of tools like valgrind and LLVM's AddressSanitizer. It's available in Clang and has been ported to GCC 4.9. To use it, specify -fsanitize=address
at the command line.
If you insist on textual replacement, a manual search-and-replace in your favorite IDE might do the trick. I wouldn't recommend it though.
A discussion in Is it good practice to NULL a pointer after deleting it? reveals that this practice is indicative of possible design problems in your program. For example, jalf's answer:
Setting pointers to NULL after you've deleted what it pointed to
certainly can't hurt, but it's often a bit of a band-aid over a more
fundamental problem: Why are you using a pointer in the first place? I
can see two typical reasons:
- You simply wanted something allocated on the heap. In which case wrapping it in a RAII object would have been much safer and cleaner.
End the RAII object's scope when you no longer need the object. That's
how
std::vector
works, and it solves the problem of accidentally
leaving pointers to deallocated memory around. There are no pointers.
- Or perhaps you wanted some complex shared ownership semantics. The pointer returned from
new
might not be the same as the one that
delete
is called on. Multiple objects may have used the object
simultaneously in the meantime. In that case, a shared pointer or
something similar would have been preferable.
My rule of thumb is that if you leave pointers around in user code,
you're Doing It Wrong. The pointer shouldn't be there to point to
garbage in the first place. Why isn't there an object taking
responsibility for ensuring its validity? Why doesn't its scope end
when the pointed-to object does?