c++11 - 获取指向派生类的弱指针

标签 c++11 inheritance visual-c++ smart-pointers

我有一堆存储为共享指针的派生类,我想知道是否有任何方法可以从对象内部获取对象的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/

相关文章:

c++ - 已弃用 API 调用的编译时检测?

c++ - 这对会被感动吗?

c++ - 无效的协变返回类型错误

c++ - (初学者)使用 Java 示例作为起点的构造函数和方法中的 C++ 继承

c++ - 在 C++ 中记录用户的最佳方式

c++ - Visual studio 6.0(VC++引用问题)

c++ - const有什么问题?

C++继承公共(public)和私有(private)?

c++ - VS2008 中的访问冲突,但 VS2002 中没有

C++ 为输入类型选择模板输出类型