Destructor for binary tree like structure?

  c++, destructor

I have a class that’s almost a binary tree except it doesn’t have a root.

class Expr {
    typedef std::tuple<char, const Expr*, const Expr*> node;
    std::variant<int, Var*, node> val;
    Expr(char op, const Expr&, const Expr&);
public:
    Expr(int x) : val(x) {};
    Expr(Var& x) : val(&x) {};
    Expr(const Expr& e);
    Expr* Clone() const { return new Expr(*this); }
    ~Expr();
    friend Expr operator+(const Expr& e1, const Expr& e2);
    friend Expr Random(const Expr& e1, const Expr& e2);
    friend Expr operator-(const Expr& e1, const Expr& e2);
    friend Expr operator*(const Expr& e1, const Expr& e2);
    friend Expr operator/(const Expr& e1, const Expr& e2);
    friend Expr operator%(const Expr& e1, const Expr& e2);
    int evaluate() const;
};

It’s always used as a temp object which Clone() is added somewhere else. So I need a destructor. I wrote this:

Expr::~Expr()
{
    if (std::holds_alternative<node>(val)) {
        delete std::get<1>(std::get<node>(val));
        delete std::get<2>(std::get<node>(val));
    }
}

But it seems like it’s deleting everything twice (and maybe even the Clone() return result, but I’m not sure), which gives an error. How do I fix this?

Source: Windows Questions C++

LEAVE A COMMENT