GLProgramming.com

home :: about :: development guides :: irc :: forums :: search :: paste :: links :: contribute :: code dump

-> Click here to learn how to get live help <-


New Paste :: Recent Pastes:: No Line Numbers


Proper memory management by Rainmaker
1
 
class CClass
{
public:
    int* pRandomData;
    char chOtherRandomData;

    CClass()
    {
        // Set any kind of pointers to data that might be allocated to NULL on initialization
        // You do that in case the data is never allocated
        pRandomData = NULL;
    }
    ~CClass()
    {
        // Now you check to see if the data is allocated
        if( pRandomData )
            // It must point to valid data, because we set it to NULL every time it doesnt
            delete [] pRandomData; // Delete it
        // Set the pointer to NULL now, so we know it doesnt contain any data
        pRandomData = NULL;
    }
    void Allocate()
    {
        // Allocate our memory - pRandomData now points to valid data
        // In reality, you should probably make sure that the data hasnt already been allocated
        // with a null check
        pRandomData = new int[100];
    }
};

void Usage()
{
    // Allocate pObject
    CClass* pObject = new CClass();
    // pObject is now valid data
    pObject->Allocate(); // Allocate the random data
    // Delete it, and it will all be deallocated
    delete pObject;

    // Now allocate pObject again
    pObject = new CClass();
    // But this time, we wont allocate the random data before we delete
    delete pObject;
    // What happens? Nothing! Because we set pRandomData to NULL at init, our destructor knew not to delete it

    // Tada!
}