Use smart pointers so that memory management is handled automatically and you are sure that you will have:
- No dangling pointers;
- There is no memory leak.
In this case, it seems to me that std::shared_ptr<> (or std::tr1::shared_ptr<> or boost::shared_ptr<> if you are not working with C ++ 11) is the right choice:
#include <memory> // For std::shared_ptr<> // ... std::shared_ptr<MyObj> obj(this->generateObj()); emit_new_signal(obj); // delete obj; // <== No need for this anymore!
Also note that the handler functions will need to accept std::shared_ptr<MyObj> , not the raw MyObj* pointer, but the code inside these handlers does not need to be changed, since std::shared_ptr provides operator -> overloading.
Note that in general, using new not recommended in C ++ 11, and if possible, use std::make_shared<> to create shared_ptr s. You might want to rewrite the generateObj() member function so that it returns std::shared_ptr<MyObj> instead of MyObj* and allows it to use std::make_shared<MyObj>() internally to create the object.
Note:
As Geier pointed out in the comments, Qt has its own QSharedPointer smart pointer class , which you can use.
source share