gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-27 22:45:32 25 4
gpt4 key购买 nike

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

谢谢

最佳答案

您所遵循的示例掩盖了所有内存管理。这可能会导致不良习惯。

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

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

没有 new 是个好消息!

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

关于c++ - 如何在C++中删除嵌套的new,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43504201/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com