如果一个对象是这样存在的:
MyClass obj;
调用成员函数:
obj.myMemberFunction();
然后在实现其目的后调用该对象的析构函数:
delete obj;
但是,假设我有一个指向对象的指针:
MyClass* obj;
调用成员函数:
obj->myMemberFunction();
现在......我如何调用这个对象的析构函数?
如果一个对象是这样存在的:
MyClass obj;
调用成员函数:
obj.myMemberFunction();
然后在实现其目的后调用该对象的析构函数:
delete obj;
但是,假设我有一个指向对象的指针:
MyClass* obj;
调用成员函数:
obj->myMemberFunction();
现在......我如何调用这个对象的析构函数?
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;
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.
运算符 delete旨在与存储在堆上分配的区域的地址的指针一起使用,这要归功于相应的运算符 new。
void function ()
{
int * pt;
pt = new int;
*pt = 42;
delete pt; // memory released
}
在堆栈上分配的内存在相应范围结束时自动释放:
void function ()
{
int i;
i = 42;
} // memory released
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;