如何在C++中删除嵌套的new

How to delete nested new in C++

ref中,他们有这行代码

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

两个问题:

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]

第二个相关问题:

How do you write this nested news with unique_ptr

谢谢

你的问题不是你要删除对象,你的问题是你要删除一个潜在的多态对象,它没有 virtual 析构函数,这使得最有可能派生 class 不会被正确清理。

See here for more information.

您所关注的示例掩盖了所有内存管理。很可能会养成坏习惯。

要正确管理内存,您可以简单地避免动态分配:

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

没有 news 是个好消息!

而且Widget真的,真的应该有一个虚拟析构函数。