How do I check if a variable, specifically a pointer, is defined in C++? Suppose I have a class:
class MyClass {
public:
MyClass();
~MyClass() {
delete pointer; // if defined!
}
initializePointer() {
pointer = new OtherClass();
}
private:
OtherClass* pointer;
};
Why worry about checking for the pointers value? Just initialize it to a null pointer value and then just call delete on it. delete on a null pointer does nothing (the standard guarantees it).
class MyClass {
public:
MyClass():pointer(0) { }
~MyClass() {
delete pointer;
pointer = 0;
}
initializePointer() {
pointer = new OtherClass();
}
private:
OtherClass* pointer;
};
And everytime you call delete on it, you should set the pointer to a null pointer value. Then you are all fine.
I tend to initialize my pointer values to NULL on object construction. This allows a check against NULL to see if the pointer variable is defined.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With