A的析构函数将在其生命周期结束时运行。如果要释放其内存并运行析构函数,则必须将其删除(如果已在堆上分配了它)。如果它是在堆栈上分配的,则会自动发生(即,当它超出范围时;请参阅RAII)。如果它是类的成员(不是指针,而是完整成员),则在包含对象被销毁时会发生这种情况。
class A
{
char *someHeapMemory;
public:
A() : someHeapMemory(new char[1000]) {}
~A() { delete[] someHeapMemory; }
};
class B
{
A* APtr;
public:
B() : APtr(new A()) {}
~B() { delete APtr; }
};
class C
{
A Amember;
public:
C() : Amember() {}
~C() {} // A is freed / destructed automatically.
};
int main()
{
B* BPtr = new B();
delete BPtr; // Calls ~B() which calls ~A()
C *CPtr = new C();
delete CPtr;
B b;
C c;
} // b and c are freed/destructed automatically
在上面的示例中,需要每个delete和delete []。在我不使用它的地方,不需要删除(或确实可以使用它)。
auto_ptr
,unique_ptr
和shared_ptr
等..非常适合做这个生命周期管理要容易得多:
class A
{
shared_array<char> someHeapMemory;
public:
A() : someHeapMemory(new char[1000]) {}
~A() { } // someHeapMemory is delete[]d automatically
};
class B
{
shared_ptr<A> APtr;
public:
B() : APtr(new A()) {}
~B() { } // APtr is deleted automatically
};
int main()
{
shared_ptr<B> BPtr = new B();
} // BPtr is deleted automatically