c++ - 我们应该在取消注册时删除观察者吗?

标签 c++ observer-pattern

Observer *o = New Observer();
Subject *s = new Subject() ;
s->register(o);

//Is it a good practice to delete the observer in the unregister function?
//I feel it is not. As the Observer object might still be in use,  for example , 
//it might be registered to another Subject. 
s->unregister(o);  

//So it is safe to rely on the client code to delete the object or rely on the smart pointer things
delete o;

我想确认我上面关于谁应该删除观察者对象的理解是否正确。

最佳答案

我同意你的看法。在注销函数中删除观察者不是一个好习惯——因为“创建资源的人必须负责删除资源”这一简单事实

这样可以避免

  • 创作者感知到的魔法行为。
  • 代码行为将被明确定义——谁创建谁就必须删除。这将为新开发人员对您的系统的开发理解奠定整体基础。

相似的主题在所有书籍中都以不同的术语进行了讨论。

关于c++ - 我们应该在取消注册时删除观察者吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6186761/

相关文章:

c++ - 使用 lambda 按降序创建字符串集

c++ - windows下驱动程序编程入门方法

ruby-on-rails - rails : Use URL Helper in Observer

android - 如何在数据绑定(bind)库中收到通知?

c++ - 指向对象的指针 vector - 如何避免内存泄漏?

c++ - 带有 std::transform 的 Visual 中的错误 C3861

c++ - C++ 标准委员会是否打算在 C++11 中 unordered_map 破坏它插入的内容?

c++ - 为什么 NULL 指针不起作用?

javascript - 浏览器 JavaScript 中的观察者模式 : subscribe to event "Dom element added" and handle this element

observer-pattern - 在 Smalltalk/VisualWorks 中实现观察者模式