Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check for pointer definedness in C++

Tags:

c++

pointers

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;

};
like image 977
tunnuz Avatar asked Nov 26 '22 22:11

tunnuz


2 Answers

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.

like image 83
Johannes Schaub - litb Avatar answered Nov 29 '22 12:11

Johannes Schaub - litb


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.

like image 25
Gabriel Isenberg Avatar answered Nov 29 '22 11:11

Gabriel Isenberg