我如何删除对象和对象中创建的对象

How do I delete object and objects created inside that object?

本文关键字:对象 创建 删除 何删除      更新时间:2023-10-16

我有两个类:FooBar

Main中创建1个Foo对象。然后我从Foo调用createBars()方法。这个方法创建了3个Bar对象。在Main中,我想删除Foo对象和由Foo对象生成的所有对象。

如何做到这一点?

代码:

int Main()
{
     Foo foo;
     foo.createBars();
}
void Foo::createBars()
{
     Bar bar1;
     Bar bar2;
     Bar bar3;
}
int Main()
{
   Foo foo; // instance created of Foo class
   foo.createBars(); // calling method createBars()
} // automatically, the instance foo goes out of scope, thus getting destructed
void Foo::createBars()
{
   Bar bar1; // create instance of class Bar bar1
   Bar bar2; // create instance of class Bar bar2
   Bar bar3; // create instance of class Bar bar3
} // all the instances bar1, bar2 and bar3 go out of scope and get destructed automatically

您没有在堆中分配任何东西,因此您不需要取消分配任何东西。

[编辑]

当你不确定一个对象的构造函数/析构函数是否被调用时,你总是可以在其中添加cout s,并找出。

下面是一个示例代码:

#include <iostream>     // std::cout
class Bar {
public:
    Bar() {
        std::cout << "Constructor of Barn";
    }
    ~Bar() {
        std::cout << "Destructor of Barn";
    }
};
class Foo {
public:
    Foo() {
        std::cout << "Constructor of Foon";
    }
    ~Foo() {
        std::cout << "Destructor of Foon";
    }
    void createBars()
    {
         Bar bar1;
         Bar bar2;
         Bar bar3;
    }
};
int main()
{
     Foo foo;
     std::cout << "After the Foo foo;n";
     foo.createBars();
     std::cout << "After the foo.createBars();n";
     return 0;
}
输出:

Constructor of Foo
After the Foo foo;
Constructor of Bar
Constructor of Bar
Constructor of Bar
Destructor of Bar
Destructor of Bar
Destructor of Bar
After the foo.createBars();
Destructor of Foo

正如Spns指出的:

是一个技术性问题。重要的是要区分动态和自动存储时间。例如,可以在堆栈上动态分配内存。

您需要手动delete对象,只有当您使用new动态地分配它们时。否则,当它们超出作用域时,将自动取消分配

这里bar1bar2bar3是函数的局部变量

只有在使用new时才需要delete

在你的例子中,你只需要声明Bar对象,不需要删除,它们会在foo作用域的末尾"删除"它们自己。