0

I am wondering if the code below will cause a memory leak and if so, how to prevent it.

Binary* binExpression = new Binary
{
        new Unary // 1
        {
            Token{TokenType::MINUS, "-",GenVal{}, 1},
            new Literal{123} // 2
        },
        Token{TokenType::STAR, "*", GenVal{}, 1},
        new Grouping // 3
        {
            new Literal{45.67} // 4
        }

};
Printer p;
p.print(binExpression);
std::cout << p.getResult() << '\n';
delete binExpression;

I am able to release only the memory pointed by binExpression (the other objects are unnamed so to speak), so what can be done about the lines marked as 1, 2, 3 and 4? Of course I can do this:

Literal* l1 = new Literal{ 123 };
Unary* u = new Unary{ Token{TokenType::MINUS, "-",GenVal{}, 1}, l1 };
Literal* l2 = new Literal{ 45.67 };
Grouping* g = new Grouping{ l2 };
Binary* binExpression = new Binary
{
    u,
    Token{TokenType::STAR, "*", GenVal{}, 1},
    g
};
Printer p;
p.print(binExpression);
std::cout << p.getResult() << '\n';
delete l1; delete l2; delete g; delete u;
delete binExpression;

Is there any better solution to this problem?

AJB
  • 97
  • 1
  • 7

1 Answers1

0

delete binExpression; calls the destructor of Binary. For objects you do not want to deal with its pointers from "outside", you implement memory cleanup in the destructor.

You might want to have a look at smart pointers too.

William
  • 1
  • 2