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
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
is broken because it will result in double delete.