views:

130

answers:

3

Which one do you prefer to delete objects? Especially in QT, but other practices are also welcome. These two alternatives seem same to me, are they?

1.Bound to another class, and destroy when it is destroyed.

SomeClass::SomeClass{
 socket_ = new QTcpSocket(this);
}

or

2.Destroy in the destructor of class

SomeClass::SomeClass{
 socket_ = new QTcpSocket();
}

SomeClass::~SomeClass{
 delete socket_;
}
+3  A: 

RAII says you should do it in the destructor of SomeClass. According to that philosophy, the SomeClass instance owns the QTcpSocket instance, so the former should fully manage the lifetime of the latter. Though both approaches are valid, I think I would prefer the one that doesn't require me to delete this.

Jon Purdy
Unfortunately most people are not that smart. Best to leave the deletion of objects to people who know what they are doing. So use a smart pointer.
Martin York
@Martin: Your statement seems rather incongruous. Of course a smart pointer is a valuable and useful tool. It's also important to know where the RAII semantics of a smart pointer come from.
Jon Purdy
Unfortunately memory management is more than just construction and destruction (RAII). You need to including copying and assignment as well as other things. All these things are done by smart pointers it is not wise to try and replicate their functionality in your own class. In modern C++ code I would not expect to see any deletes (unless you write smart pointers, it should all be hidden inside smart pointers or smart containers)
Martin York
You're right, of course. So wrap the thing in a smart pointer! My answer is still perfectly valid. I still don't see what you're getting at.
Jon Purdy
+8  A: 

When in Rome, do as the Romans do. If your framework uses one method (for example Qt relies on parent-child relationship), use this method in your code.

Of course don't forget about general good memory management practices: create object on stack whenever it's possible, use shared pointers, etc.

chalup
+1 consistency with existing code is important.
Mark B
A: 

For me, I think that it's better select the short way to write code (1), but with best-practice in mind, because Qt do it (destroy user defined variables) for you.

mosg