c++ - C++ `enable_shared_from_this` 和 `shared_From_this()` 未编译或运行
问题描述
我很难尝试使用 clang 编译器编译以下代码。我不确定我是否以正确的方式使用enable_shared_from_this
and 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;
}
解决方案
推荐阅读
- oracle - PL-SQL 循环遍历值以获取动态查询和存储结果
- java - 如何在 bean 类中使用 groupBy
- c# - 与 gRPC 的进程内通信
- firebase - “ task.future.then ” 在我的 Flutter 代码中不断抛出错误
- css - 在多列中组织列表项
- javascript - 如何测试使用 props.history 的按钮 onClick 在 rtl 中的功能?
- php - 在 php 中给出的变量中显示选择的字符串
- google-bigquery - 如何将应用程序的旧分析数据从 firebase 获取到 bigquery?
- python - 如何合并具有一定数量共同子字符串的字符串以在 Python 的数据框中生成一些组
- html - 我如何制作我所有的列表段落,对齐相同