5

我正在学习智能指针和shared_from_this. 在类继承关系中,这将很难理解。

我有两个基类CAand CB,它们派生自enable_shared_from_this,子类CC派生自CAand CB。我想从类 self 中取出三个类的共享指针,所以我写了sharedCAfromThis,sharedCBfromThissharedCCfromthis.

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;
    }
};
4

2 回答 2

4

您应该从enable_shared_from_this. 根据[util.smartptr.shared.const]/1

在下面的构造函数定义中,对于type的指针,启用shared_­from_­this with意味着如果具有明确且可访问的基类,该基类是 的特化 ,则应隐式转换为并且构造函数评估语句:ppY*Yenable_­shared_­from_­thisremove_­cv_­t<Y>*T*

if (p != nullptr && p->weak_this.expired())
  p->weak_this = shared_ptr<remove_cv_t<Y>>(*this, const_cast<remove_cv_t<Y>*>(p));

对成员的分配weak_­this不是原子的,并且与对同一对象([intro.multithread])的任何潜在并发访问冲突。

如果您使用私有继承,则无法再访问基类。

于 2019-08-31T14:06:27.707 回答
0

看起来您的问题是您有重复项。您需要确保只有一个enable_shared_from_this.

要使用类做到这一点,您可以虚拟地派生类:

class A : virtual public enable_shared_from_this<A> ...
class B : virtual public enable_shared_from_this<B> ...

class C : public A, public B ...

现在您有一个 的实例,enable_shared_from_this<>这应该可以按预期工作。否则,它可能会使用 B 中可能是 a 的版本nullptr,因此会出现错误。

于 2021-12-24T17:33:01.617 回答