我正在学习智能指针和shared_from_this
。在Class Inheritance Relations中,会很难理解。
我有两个基类CA
和CB
,它们派生自enable_shared_from_this
,子类CC
派生自 CA
和 CB
。
我想从类自身中取出三个类的共享指针,所以我写了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;
}
};
最佳答案
您应该公开继承自 enable_shared_from_this
.每[util.smartptr.shared.const]/1 :
In the constructor definitions below, enables
shared_from_this
withp
, for a pointerp
of typeY*
, means that ifY
has an unambiguous and accessible base class that is a specialization ofenable_shared_from_this
, thenremove_cv_t<Y>*
shall be implicitly convertible toT*
and the constructor evaluates the statement:if (p != nullptr && p->weak_this.expired()) p->weak_this = shared_ptr<remove_cv_t<Y>>(*this, const_cast<remove_cv_t<Y>*>(p));
The assignment to the
weak_this
member is not atomic and conflicts with any potentially concurrent access to the same object ([intro.multithread]).
如果你使用私有(private)继承,基类就不能再访问了。
关于c++ - 在抛出 'std::bad_weak_ptr' what() : bad_weak_ptr? 实例后终止调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57738379/