memory management - C++ unique_ptr and observer pattern best practices -
i'm trying write correct c++11 application, , i'm faced problem of memory management observer design pattern.
my emitter , listeners owned same class, stored in std::unique_ptr
. code think write should this:
class listener { emitter &myemitter; public: listener(emitter &emiter): myemitter(emitter) { myemitter.register(*this); } virtual ~listener() { myemitter.unregister(*this); } } class emitter { std::vector<listener*> mylisteners; public: void register(listener &listener) { mylisteners.push_back(&listener); } void unregister(listener &listener) { mylisteners.erase(std::remove(mylisteners.begin(), mylisteners.end(), &listener)); } } class owner { std::unique_ptr<listener> thelistener; std::unique_ptr<emitter> theemitter; }
is correct approach ?
Comments
Post a Comment