How to avoid lb from getting leak with the situation below
//A.h
class A : public Gtk::Button{
A();
};
//A.cc
A::A(){
Gtk::Label *lb = new Gtk::Label("text");
lb->show();
this->add(*lb);
}
A::~A(){}
//main.cc
A *a = new A();
//I do something here with a and then delete it
delete a;
//continue on with the program..
Ok i know lb in my a object is leaking. My question is,is there a better way to fix this rather than have lb declare outside the constructor scope and delete it with the destructor?
I don't know if it's applicable in GTK (since I gave up on it quite early) but in Qt similar situation the solution is to give it a parent that control your user-created objects. Thus you don't have to worry about deleting them.
In other words I would do lb child of A and let A handle its memory destruction instead.
If your object only has a use in the body of one function and is not needed after the function, you can just allocate it on the stack instead of using new. It will be destroyed as soon as you exit the function (or as soon as the scope where it was constructed is exited).
And if A is only doing something like you wrote in your post, you could even just make it a function with the constructor's code and don't worry about allocating an object for that