I just ran into a minor problem regarding pointers. As I wanted to have a quick and easy way to do this task in a single line:
...
delete pointer;
pointer = 0;
...
I just quickly set up a simple header file with a template method that accepts any type of pointer. It looks like this:
#ifndef P_DELETE_H
#define P_DELETE_H
template <typename T>
void pDelete(T* pointer) {
if (pointer) {
delete pointer;
pointer = 0;
}
}
#endif
However, the results don't meet my expectations of the object beeing deleted and the pointer beeing reset. Instead, it seems that only the object was deleted, but setting it to zero had no effect (which is what I'd need). If somebody here could lighten me up a little and explain this behavior, I'd apreceate that much!
UPDATE:
As the answers explain, using std::unique_ptr and std::shared_ptr is the safer way to go than nullifying this pointers.
But if you really need to go such way as I requested, the following code will do the trick:
template <typename T>
inline void pDelete(T*& pointer) {
if (pointer) {
delete pointer;
pointer = 0;
}
}
However, this is generally unsafe to use, even though it correctly deletes and nullifies the pointer on all instances (quick test revealed this).
Thanks to everyone for the informative answers!
The solution you're looking for is:
Yeah, just write that code in-line. There's really no reason to introduce another function template somewhere that people will have to look up to figure out what it actually does, just to save one line of code.
The above is perfectly readable and easy to understand.