[英]What is the difference between delete and free in C++ and which one is called by the C++'s default destructor?
[英]What is the difference between delete and calling destructor in C++
如标题所述,这是我的代码:
class Foo {
public:
Foo (int charSize) {
str = new char[charSize];
}
~Foo () {
delete[] str;
}
private:
char * str;
};
对于这个类,有什么区别:
int main () {
Foo* foo = new Foo(10);
delete foo;
return 0;
}
和
int main () {
Foo* foo = new Foo(10);
foo->~Foo();
return 0;
}
调用析构函数会释放该对象拥有的资源,但它不会释放分配给该对象本身的内存。 第二个代码段有内存泄漏。
每当调用析构函数时,都不会释放对象的已分配内存,但程序中不再可以访问该对象。 但删除完全从内存中删除对象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.