whi*_*ok6 7 c++ inheritance boost subclass shared-ptr
我需要找到一个解决方案,允许子类获得正确的智能指针.
class Parent : public enable_shared_from_this {
...
}
class Child : public Parent {
public Child(){
boost::shared_ptr<Parent> pointer=shared_from_this(); // should work
boost::shared_ptr<Child> pointer=shared_from_this(); // won't work.
...
}
Run Code Online (Sandbox Code Playgroud)
如何使用shared_from_this()获得正确的智能指针?
背景:
我正在写一些通知器/监听器的东西,有些类自然需要从通知器注册和取消注册.例如,
class Body : extends Listener<BodyMessage>{ // listen for BodyMessage messages
public:
Body() {
Notifier<BodyMessage>::register(this); // register with the appropriate notifier
}
virtual ~Body {
Notifier<BodyMessage>::unregister(this); // unregister
}
bool notify(BodyMessage m){ ... }
...
}
Run Code Online (Sandbox Code Playgroud)
通常我会使用这个指针,一切都会好的.我已经让Notifier使用模板,因此我只能将消息传递给想要听到它们的消息.
但是,我想使用智能指针.如果通知程序如下所示:
template<typename t>
class Notifier {
public:
static void register<boost::shared_ptr<Listener<t>>> boost::shared_ptr<Listener<t>> listener);
...
}
Run Code Online (Sandbox Code Playgroud)
然后我再也不能使用这个指针了.当然,我让Body扩展了enable_shared_from_this:
class Body : public boost::enable_shared_from_this, public Listener<BodyMessage> {
public:
Notifier<BodyMessage>::register(get_shared_ptr());
...
}
Run Code Online (Sandbox Code Playgroud)
这似乎适用于身体.但是,对于实体的子类(或者,至少它似乎不是),它不起作用:
class BodyChild : public Body {
public:
BodyChild(){
Notifier<BodyMessage>::register(get_shared_ptr());
}
Run Code Online (Sandbox Code Playgroud)
可能是因为我无法施放shared_pointer.那么,我能解决这个问题吗?
我对其他想法持开放态度,但如果我能让它发挥作用,我会很激动.
您可以投射智能指针,Boost为您提供了一些模板来简化这一过程.你有例如.static_pointer_cast并dynamic_pointer_cast允许您通过指针投射.
由于this是正确的动态类型,您可以调用boost::static_pointer_cast返回值shared_from_this():
boost::shared_ptr<Child> p = static_pointer_cast<Child>(shared_from_this());
Run Code Online (Sandbox Code Playgroud)
(无需static_pointer_cast感谢Koenig查询)
| 归档时间: |
|
| 查看次数: |
2482 次 |
| 最近记录: |