【问题标题】:Visitor design pattern in cpp with smart pointers is giving runtime error [duplicate]cpp中带有智能指针的访问者设计模式给出运行时错误[重复]
【发布时间】:2022-02-03 18:25:54
【问题描述】:

我正在尝试为我的项目实现类似于此 sn-p 的访问者模式。 但是代码正在吐出运行时错误。它打印的错误是bad_weak_ptr .代码本身似乎是正确的,我找不到设计模式的任何问题。 这可能是由于智能指针而发生的。

template<class T> class Beignet;
template<class T> class Cruller;

template<class T>
class PastryVisitor {
    public:
    virtual T visitBeignet(shared_ptr<Beignet<T>> beignet) = 0;
    virtual T visitCruller(shared_ptr<Cruller<T>> cruller) = 0;
};

template<class T>
class Pastry {
    public:
    virtual T accept(shared_ptr<PastryVisitor<T>> visitor) = 0;
};

template<class T>
class Beignet : public Pastry<T>, enable_shared_from_this<Beignet<T>> {
    
    public:
    T accept(shared_ptr<PastryVisitor<T>> visitor) override {
        return visitor->visitBeignet( this->shared_from_this() );
    }
};

template<class T>
class Cruller : public Pastry<T>, enable_shared_from_this<Pastry<T>> {
    
    public:
    T accept(shared_ptr<PastryVisitor<T>> visitor) override {
        return visitor->visitCruller( this->shared_from_this() );
    }
};

class PastryPrinter : public PastryVisitor<string>, enable_shared_from_this<PastryPrinter> {

    public:
    string print(shared_ptr<Pastry<string>> pastry) {
        return pastry->accept( shared_from_this() );
    }

    string visitBeignet(shared_ptr<Beignet<string>> beignet) override {
        return "Beignet";
    }

    string visitCruller(shared_ptr<Cruller<string>> cruller) override {
        return "Cruller";
    }

};

int main() {
    auto pastry = make_shared<PastryPrinter>();
    shared_ptr<Pastry<string>> chocolateBeignet = make_shared<Beignet<string>>();
    pastry->print(chocolateBeignet);
}

【问题讨论】:

标签: c++ oop c++17


【解决方案1】:

您私下继承std::enable_shared_from_this。它必须公开继承才能工作:

class Cruller : public Pastry<T>, public enable_shared_from_this<Pastry<T>>

在其他类中也是如此。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-05-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多