mercredi 15 mai 2019

store event-object as member or as a shared_ptr

I have an event-object that should be a member of a class:

class foo
{
public:
    Event event_;
}

functions can subscribe to this event and get called when invoke is called on the event:

Foo * foo = new Foo();
Event & event_ = foo->event_;
int id = event_.Subscribe(*some std::function<void()>*);
event_.Invoke();

// a lot of stuff happens until we no longer need to be subscribed to the event

event_.Unsubscribe(id);

Now, let's assume this object foo gets deleted before we unsubscribe for whatever reason. To prevent this i could make the event a shared_ptr.

class foo
{
public:
    std::shared_ptr<Event> event_;
}

Is this is conceptually wrong? Can, given a good design, an unsubscribe never happen before the object is destroyed? Am i hiding potential errors/memory leaks by making it a shared_ptr? or is this good practice?

For everybody interested in the complete event-system in c++.

Aucun commentaire:

Enregistrer un commentaire