Quote Originally Posted by srvolatile View Post
Hi,
Please go through the below code.
What if Initialize() fails for some reason, and then your object is destroyed? You now have a double "delete" error, since you called delete before the Initialize() call, and you're calling delete a second time in the destructor.

In this day and age of C++, there is no such need for the back-and-forth, spaghetti-like coding of operator new in one function, and delete in another function. What you need is a reference-counted smart pointer, possibly shared_ptr(), so that the real deletion only occurs when it needs to.
Code:
#include <memory>

class PlotDraw
{
    typedef std::shared_ptr<Graphics::TBitmap> BitmapPtr;
    public : 
        BitmapPtr DrawnBitmap;
        PlotDraw(TComponent *Owner);
       ~PlotDraw();
        Initialise();
        Drawing(TObject *Sender);
};

PlotDraw::PlotDraw(TComponent *Owner) : DrawnBitmap(new Graphics::TBitmap)  // initial allocation
{
    // To get the TBitmap pointer
    // Graphics::TBitmap* pBitmap = DrawnBitmap.get();
    Initialise(); 
}

PlotDraw::Initialise()
{ 
   // no need to allocate
}

PlotDraw::~PlotDraw
{
  // no need to call delete explicitly.  If the smart pointer reference count is not 0, 
  // it will call delete for you, otherwise, it won't call delete
}

// method calls with the various events
PlotDraw::Drawing(TObject *Sender)
{
    DrawnBitmap.reset(new Graphics::TBitmap);  // reallocation takes place here
    Initialse();
}
The question is still whether you need to reallocate each time, but the code will not have the double deletion error you would have gotten. To get the internal pointer, use the .get() method on DrawnBitmap. Note that there are no calls whatsoever to delete. The shared_ptr takes care of all of these details.

Regards,

Paul McKenzie