gpt4 book ai didi

c++ - 在抛出 'std::bad_weak_ptr' what() : bad_weak_ptr? 实例后终止调用

转载 作者:搜寻专家 更新时间:2023-10-31 02:02:12 37 4
gpt4 key购买 nike

我正在学习智能指针和shared_from_this。在Class Inheritance Relations中,会很难理解。

我有两个基类CACB,它们派生自enable_shared_from_this,子类CC 派生自 CACB。我想从类自身中取出三个类的共享指针,所以我写了sharedCAfromThissharedCBfromThissharedCCfromthis

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 with p, for a pointer p of type Y*, means that if Y has an unambiguous and accessible base class that is a specialization of enable_­shared_­from_­this, then remove_­cv_­t<Y>* shall be implicitly convertible to T* 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/

37 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com