首页 > 解决方案 > C++ `enable_shared_from_this` 和 `shared_From_this()` 未编译或运行

问题描述

我很难尝试使用 clang 编译器编译以下代码。我不确定我是否以正确的方式使用enable_shared_from_thisand shared_From_this() ,或者无意中违反了规则。有人可以指出究竟是什么导致了问题。

#include <iostream>
#include <memory>

class IB {
public:
    virtual void Calle() =0;
    virtual void Show() = 0;
};

class IC {
public:
    virtual void Calle() =0;
    virtual void Print() =0;
};

class CB;
class CC;

class CA : public std::enable_shared_from_this<CA> {
private:
    std::shared_ptr<IB> m_ib;
public:
    CA()
    : m_ib(std::make_shared<CB>(shared_from_this())) {
        std::cout << "Created CA obj\n";
    }
    void Calle() {
        if(m_ib) m_ib->Calle();
        // Show();
    }
    void Show() {
        std::cout << "Printing from here. CA\n";
    }
};

class CB : public IB, public std::enable_shared_from_this<CA> {
private:
    std::shared_ptr<IC> m_ic;
    std::shared_ptr<CA> m_ca;
public:
    CB() : CB(nullptr){}
    CB(const std::shared_ptr<CA> a)
    : m_ca(a)
    , m_ic(std::make_shared<CC>(shared_from_this())) {
        std::cout << "Created CB obj\n";
    }
    virtual void Calle() override;
    virtual void Show() override; 
};

void CB::Calle() {
    if(m_ca) m_ca->Show();
    if(m_ic) m_ic->Print();
    Show();
}
void CB::Show() {
    std::cout << "Printing from here. CB\n";
}

class CC : public IC, public std::enable_shared_from_this<CA> {
private:
    std::shared_ptr<IB> m_ib;
public:
    CC() 
    : CC(nullptr){}
    CC(const std::shared_ptr<CB> b) 
    : m_ib(b){
        std::cout << "Created CC obj\n";
    }
    virtual void Calle() override;
    virtual void Print() override;
};

void CC::Calle() {
    if(m_ib) m_ib->Show();
}
void CC::Print() {
    std::cout << "Printing from here. CC\n";
}

int main() {

    auto a = std::make_shared<CA>();
    a->Calle();

    return 0;
}

标签: c++smart-pointers

解决方案


推荐阅读