使用(this)向观察者注册的共享指针 [英] Shared pointer using (this) registering to an observer

查看:117
本文介绍了使用(this)向观察者注册的共享指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在尝试使用要注册到观察者的类中的共享指针时,我遇到了问题.

I am having a problem trying to use a shared pointer from a class that wants to register to an observer (using ) here is the example.

Observer.hpp

Observer.hpp

class Observer {
virtual void update() = 0;
}

Consumer.hpp

Consumer.hpp

class Consumer : public Observer {
virtual void update() override;
}

Consumer.cpp

Consumer.cpp

class Consumer {
***

这不起作用-如何使用共享指针做到这一点?

register.registerObserver(std::make_shared<Observer>(this));
}

Register.cpp

Register.cpp

class Register {
void registerObserver(const std::shared_ptr<Observer>& observer);
}

推荐答案

请勿使用 shared_ptr .

You should never use make_shared or otherwise construct a shared_ptr from this.

此外,除非绝对确定您完全了解并了解自己在做什么,否则永远不要结合使用内存管理技术.

Additionally never combine memory management techniques unless you're absolutely sure you know and understand completely what you are doing.

如果确实需要引用当前对象的shared_ptr,则应改为将对象构造为shared_ptr,并让该类继承

If you really need a shared_ptr referencing the current object you should instead construct the object as a shared_ptr the first time and have the class inherit enable_shared_from_this.

之后,当您需要共享指针时,请使用 shared_from_this

After that when you need the shared pointer use shared_from_this

由于有一个对象,因此您已经构造了对象,并使用直接指针从该对象创建另一个共享指针,一旦您的shared_ptr引用之一达到0,您的引用就会被破坏,而另一个则具有无效的引用参考.

Since you have a this you have already constructed your object and using the direct pointer to create another shared pointer from it will result in your reference getting destroyed as soon as one of your shared_ptr references reach 0, leaving the other having a invalid reference.

这篇关于使用(this)向观察者注册的共享指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆