Object Deletion: use parent or not
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?
Bound to another class, and destroy when it is destroyed.
SomeClass::SomeClass{ socket_ = new QTcpSocket(this); }
or
Destroy in the destructor of class
SomeClass::SomeClas开发者_开发问答s{ socket_ = new QTcpSocket(); } SomeClass::~SomeClass{ delete socket_; }
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.
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
.
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.
精彩评论