Search code examples
c++raii

How to delete nested new in C++


In ref, they have this line of code

Widget *aWidget = new BorderDecorator(new BorderDecorator(new ScrollDecorator
(new TextField(80, 24))));

Two questions:

Say, I want to explicitly delete the objects created with new. How do you do that?

BTW, If I just add

delete aWidget; 

I get warning: deleting object of abstract class type 'Widget' which has non-virtual destructor will cause undefined behaviour [-Wdelete-non-virtual-dtor]

Second related question:

How do you write this nested news with unique_ptr

Thanks


Solution

  • The example you're following glosses over all the memory management. It's likely to lead to bad habits.

    To properly manage memory, you could simply avoid dynamic allocations:

    TextField textField(80, 24);
    ScrollDecorator scrollDecorator(&textField);
    BorderDecorator bd1(&scrollDecorator);
    BorderDecorator bd2(&bd1);
    Widget *aWidget = &bd2;
    

    No news is good news!

    And Widget really, really should have a virtual destructor.