[英]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
,它是专门为此设计的:
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
std :: weak_ptr对临时所有权建模:当仅当对象存在时才需要访问该对象,并且该对象可能随时被其他人删除时,std :: weak_ptr用于跟踪该对象
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.