【发布时间】:2019-08-31 13:23:13
【问题描述】:
我正在学习智能指针和shared_from_this。在类继承关系中,会非常难理解。
我有两个基类CA 和CB,它们派生自enable_shared_from_this,子类CC 派生自CA 和CB。
我想从类self中取出三个类的共享指针,所以我写了sharedCAfromThis、sharedCBfromThis和sharedCCfromthis。
class CA : private enable_shared_from_this<CA> {
public:
shared_ptr<CA> sharedCAfromThis() { return shared_from_this(); }
virtual ~CA() {};
void print() {
cout << "CA" << endl;
}
};
class CB : private enable_shared_from_this<CB> {
public:
shared_ptr<CB> sharedCBfromThis() { return shared_from_this(); }
virtual ~CB() {};
void print() {
cout << "CB" << endl;
}
};
class CC : public CA, CB {
public:
shared_ptr<CC> sharedCCfromThis() { return dynamic_pointer_cast<CC>(sharedCAfromThis()); }
virtual ~CC() {};
void print() {
cout << "CC" << endl;
}
};
int main()
{
shared_ptr<CC> cc_ptr = make_shared<CC>();
cc_ptr->sharedCAfromThis()->print();
//shared_ptr<C> c_ptr = make_shared<C>();
//c_ptr->get_shared_b()->printb();
while (1);
}
但我错了问题是:
This application has requested the Runtime to terminate it in an unusual way.
Please contact the application's support team for more information.
terminate called after throwing an instance of 'std::bad_weak_ptr'
what(): bad_weak_ptr
为什么我会收到此错误消息?
你好,是的,非常感谢,我把private改成public了,但是问题依旧存在。我的 gcc 版本是 8.0;我将代码更改如下。
class CA : public enable_shared_from_this<CA> {
public:
shared_ptr<CA> sharedCAfromThis() { return shared_from_this(); }
virtual ~CA() {};
void print() {
cout << "CA" << endl;
}
};
class CB : public enable_shared_from_this<CB> {
public:
shared_ptr<CB> sharedCBfromThis() { return shared_from_this(); }
virtual ~CB() {};
void print() {
cout << "CB" << endl;
}
};
class CC : public CA, CB, enable_shared_from_this<CC> {
public:
shared_ptr<CC> sharedCCfromThis() { return dynamic_pointer_cast<CC>(sharedCAfromThis()); }
virtual ~CC() {};
void print() {
cout << "CC" << endl;
}
};
【问题讨论】:
-
reference 中不清楚的地方即。公共继承是强制性的 ?
-
是的,公共继承是强制性的
-
@rafix07 不清楚的部分是根据this reference,从C ++ 17开始才需要,问题没有指定标准版本。
-
@Yksisarvinen 在没有明确指定语言版本的情况下,我认为假设 当前最新版本 是相当合理的 - 目前是 C++17。
标签: c++ inheritance shared-ptr weak-ptr enable-shared-from-this