我正在学习智能指针和shared_from_this
. 在类继承关系中,这将很难理解。
我有两个基类CA
and CB
,它们派生自enable_shared_from_this
,子类CC
派生自CA
and 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;
}
};