samedi 28 mars 2020

Observer pattern, smart pointers and singleton classes

I want to create an Obserer pattern using smart pointers. This is my class:

class Observable {
public:
    void addObserver(std::shared_ptr<Observer> ptr);
private:
    std::list<std::weak_ptr<Observer>> observers;
};

The use of smart pointers provides strong guarantees about memory leak, however I don't understand how to manage list of observers when I don't have a shared_ptr. Example for singleton classes:

class Singleton {
private:
  Singleton();
public:
  static Singleton& getInstance() {
      static Signleton instance;
      return instance;
  }
}

In this case I don't have a shared ptr but the singleton class can be an observer. Does it mean that I need to return a shared_ptr from a singleton class? Is there any design detail to take into account?

Aucun commentaire:

Enregistrer un commentaire