获取指向派生 class 的弱指针
Getting weak pointer to derived class
我有一堆派生的 classes 存储为共享指针,我想知道是否有任何方法可以从对象内部获取对象的 weak_ptr
?
我试过使用 shared_from_this()
函数,但问题是因为它是派生的 class,当我使基础 class 继承自 enable_shared_from_this
时,当派生 class 调用 shared_from_this()
时,它得到 base class not[=27= 的 shared_ptr
] derived class 我无法将其转换为 class
的 shared_ptr
有什么建议吗?
正如@Torbjörn 所说,使用 dynamic_pointer_cast<Derived>(base_ptr)
解决了这个问题,因为它允许我将 shared_ptr
向下转换为继承,这是不允许的。
Usign CRTP你可以实现它:
#include <memory>
template<typename T>
struct B: std::enable_shared_from_this<T> {};
struct D: B<D> {};
int main() {
std::shared_ptr<B<D>> b = std::make_shared<D>();
std::shared_ptr<D> d = b->shared_from_this();
std::weak_ptr<D> w = b->shared_from_this();
}
如果你想要一个通用的、非模板的基础class,你可以依赖像双重调度这样的技术,如下例所示:
#include <memory>
#include <iostream>
struct D1;
struct D2;
struct S {
void doSomething(std::weak_ptr<D1> weak) { std::cout << "D1" << std::endl; }
void doSomething(std::weak_ptr<D2> weak) { std::cout << "D2" << std::endl; }
};
struct B: std::enable_shared_from_this<B> {
virtual void dispatch(S &) = 0;
};
template<typename T>
struct M: B {
void dispatch(S &s) override {
auto ptr = std::static_pointer_cast<T>(shared_from_this());
s.doSomething(ptr);
}
};
struct D1: M<D1> {};
struct D2: M<D2> {};
int main() {
std::shared_ptr<B> b = std::make_shared<D1>();
S s;
b->dispatch(s);
}
我有一堆派生的 classes 存储为共享指针,我想知道是否有任何方法可以从对象内部获取对象的 weak_ptr
?
我试过使用 shared_from_this()
函数,但问题是因为它是派生的 class,当我使基础 class 继承自 enable_shared_from_this
时,当派生 class 调用 shared_from_this()
时,它得到 base class not[=27= 的 shared_ptr
] derived class 我无法将其转换为 class
shared_ptr
有什么建议吗?
正如@Torbjörn 所说,使用 dynamic_pointer_cast<Derived>(base_ptr)
解决了这个问题,因为它允许我将 shared_ptr
向下转换为继承,这是不允许的。
Usign CRTP你可以实现它:
#include <memory>
template<typename T>
struct B: std::enable_shared_from_this<T> {};
struct D: B<D> {};
int main() {
std::shared_ptr<B<D>> b = std::make_shared<D>();
std::shared_ptr<D> d = b->shared_from_this();
std::weak_ptr<D> w = b->shared_from_this();
}
如果你想要一个通用的、非模板的基础class,你可以依赖像双重调度这样的技术,如下例所示:
#include <memory>
#include <iostream>
struct D1;
struct D2;
struct S {
void doSomething(std::weak_ptr<D1> weak) { std::cout << "D1" << std::endl; }
void doSomething(std::weak_ptr<D2> weak) { std::cout << "D2" << std::endl; }
};
struct B: std::enable_shared_from_this<B> {
virtual void dispatch(S &) = 0;
};
template<typename T>
struct M: B {
void dispatch(S &s) override {
auto ptr = std::static_pointer_cast<T>(shared_from_this());
s.doSomething(ptr);
}
};
struct D1: M<D1> {};
struct D2: M<D2> {};
int main() {
std::shared_ptr<B> b = std::make_shared<D1>();
S s;
b->dispatch(s);
}