简体   繁体   中英

Observer with shared pointers

I am trying to write a simple observer class which registers and holds the object's shared pointer. Below is the code:

template <typename Ptr>
class S
{
  private:
    std::map<string,std::vector<shared_ptr<Ptr>> observers_;
  public:

  S()=default;

  void registerObserver(const string &event, shared_ptr<Ptr> observer)
  {
    observers_[event].push_back(observer);
  }

  void notify(const string&event) 
  {
    for (const auto& obs : observers_.at(event)) 
      obs->notify();
  }

};

This however fails compilation with this error:

Subject.h:51:50: error: template argument 2 is invalid
   51 |     std::map<string,std::vector<shared_ptr<Ptr>> observers_;

Can some one please help correct my declaration?

I am trying to write a simple observer class which registers and holds the object's shared pointer.

Then you want to use std::weak_ptr , which are specifically designed for this:

std::weak_ptr models temporary ownership: when an object needs to be accessed only if it exists, and it may be deleted at any time by someone else, std::weak_ptr is used to track the object

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM