Recently I learned that using smart ptr could make our work easier. I tried to add boost::scoped_ptr into my code. However, I’m quite not sure whether I should delete a pointer to class. Here is my code:
class onTimeStepOp : public QWidget
{
public:
//some function here
~onTimeStepOp(){delete xr;}
private:
xmlReader *xr;
//others.
};
for(int i = m; i >= 1; --i) {
boost::scoped_ptr<onTimeStepOp> otso(new onTimeStepOp(
QString::number(currentFrameNum - i),
QString::number(currentFrameNum)
));
//do something here.
}
It seems that the otso will call its destructor at the end of the scope. So I added the destructor into the class. The program crashed after running. However, without the destructor, it seems that the program is leaking memory with the help of Valgrind. I’m quite confused about that. Does it mean that deletion is unnecessary(May be deleting a freed memory for the second time? I’m not sure about that) when using smart pointer and how does the code crash?
A smart pointer will only invoke the destructor of the instance it’s holding. If that instance happens to have other dynamically allocated members, those are not cleaned up automatically (unless you hold them in smart pointers too!)
So in your case, hold the member in a smart pointer too (
boost::scoped_ptrorboost::shared_ptretc.)