3

如果一个对象是这样存在的:

MyClass obj;

调用成员函数:

obj.myMemberFunction();

然后在实现其目的后调用该对象的析构函数:

delete obj;

但是,假设我有一个指向对象的指针:

MyClass* obj;

调用成员函数:

obj->myMemberFunction();

现在......我如何调用这个对象的析构函数?

4

4 回答 4

6

You've got it backwards; do delete in the second case and not the first:

MyClass obj;
obj.myMemberFunction();
//delete obj;
//^^^^^^^^^^^
// NO! `obj` has automatic storage and will
// be destroyed automatically when it goes out
// of scope.

delete expects a pointer to a dynamically-allocated object:

MyClass* obj = new MyClass;
obj->myMemberFunction();
delete obj;
于 2012-11-03T17:16:43.637 回答
2

If you create it with

MyClass obj;

you do nothing to delete it. If you create it with

MyClass* obj = new MyClass();

you use

delete obj;

to delete it.

于 2012-11-03T17:17:22.543 回答
2

运算符 delete旨在与存储在堆上分配的区域的地址的指针一起使用,这要归功于相应的运算符 new

void function () 
{
  int * pt;

  pt = new int;

  *pt = 42;

  delete pt; // memory released
}

在堆栈上分配的内存在相应范围结束时自动释放:

void function () 
{
  int i;

  i = 42;

} // memory released
于 2012-11-03T17:26:14.960 回答
0

When you write MyClass obj;, the object is allocated on the stack, as opposed to on the heap. In this case, the object is destroyed automatically then it goes out of scope. The compiler generates code to ensure the destructor is called. So you don't delete the object explicitly.

delete is used when an object is allocated on the heap. For example:

MyClass* pobj = new MyClass;
// Do something with pobj...
delete pobj;
于 2012-11-03T17:18:33.823 回答