我有一堆存储为共享指针的派生类,我想知道是否有任何方法可以从对象内部获取对象的weak_ptr
?
我试过使用 shared_from_this()
函数,但问题是因为它是一个派生类,当我让基类继承自 enable_shared_from_this
时,当派生类调用 shared_from_this()
它获取基类 不是 派生类<的shared_ptr
/em> 我无法将其转换为派生类的 shared_ptr
有什么建议吗?
最佳答案
使用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();
}
如果你想要一个通用的、非模板的基类,你可以依赖像双重调度这样的技术,如下例所示:
#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);
}
关于c++11 - 获取指向派生类的弱指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38628094/