我如何删除对象和对象中创建的对象
How do I delete object and objects created inside that object?
我有两个类:Foo
和Bar
。
在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
动态地分配它们时。否则,当它们超出作用域时,将自动取消分配。
这里bar1
、bar2
和bar3
是函数的局部变量
只有在使用new
时才需要delete
。
在你的例子中,你只需要声明Bar对象,不需要删除,它们会在foo作用域的末尾"删除"它们自己。
相关文章:
- 如何为模板化对象创建模板向量?VS正在投掷C3203
- 具有包含其他对象的类的对象创建顺序
- 为什么我们再次从结构对象创建结构变量?
- 将对象创建为全局/静态对象会崩溃,而本地对象不会崩溃
- 如何创建一个对象创建函数,该函数将由与其关联的名称调用?
- 如何为自定义模板对象创建专门的函数模板
- 对象创建错误的C++矢量
- 如何为Python Swigged C++对象创建和分配回调函数
- 在 C++ 中为 C 样式对象创建一个透明包装类
- 此类模板的对象创建如何工作?
- C++ 中的对象创建类型有什么区别?
- 未知大小的数组作为类成员,用于在运行时(对象创建时间)创建数组的对象
- 如何仅通过父类对象限制对象创建
- 在正确性或良好的代码结构方面,这种动态对象创建看起来如何
- 无法将类对象创建为另一个类的成员
- 如何从现有基类对象创建派生类对象
- 在 DTor 之前删除的静态对象创建的线程?
- C++:定义多个构造函数时的对象创建/销毁序列
- 从对象创建矢量包装器,该对象只允许使用索引访问向量
- 是否可以为CPP中的对象创建一组指针