When should we use std::enable_shared_from_this

后端 未结 3 1555
逝去的感伤
逝去的感伤 2020-12-29 08:54

I just knew std::enable_shared_from_this form this link.
But after reading the code below, I don\'t know when to use it.

try {
        G         


        
3条回答
  •  礼貌的吻别
    2020-12-29 09:19

    Let's say I want to represent a computation tree. We'll have an addition represented as a class deriving from expression with two pointers to expressions, so an expression can be evaluated recursively. However, we need to end the evaluation somewhere, so let's have numbers evaluate to themselves.

    class Number;
    
    class Expression : public std::enable_shared_from_this
    {
    public:
        virtual std::shared_ptr evaluate() = 0;
        virtual ~Expression() {}
    };
    
    class Number : public Expression
    {
        int x;
    public:
        int value() const { return x; }
        std::shared_ptr evaluate() override
        {
            return std::static_pointer_cast(shared_from_this());
        }
        Number(int x) : x(x) {}
    };
    
    class Addition : public Expression
    {
        std::shared_ptr left;
        std::shared_ptr right;
    public:
        std::shared_ptr evaluate() override
        {
            int l = left->evaluate()->value();
            int r = right->evaluate()->value();
            return std::make_shared(l + r);
        }
        Addition(std::shared_ptr left, std::shared_ptr right) :
            left(left),
            right(right)
        {
    
        }
    };
    

    Live on Coliru

    Note that the "obvious" way of implementing Number::evaluate() with return std::shared_ptr(this); is broken because it will result in double delete.

提交回复
热议问题