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/