如何删除有指针成员的类的指针? [英] How delete a pointer of classes which has pointer members?
本文介绍了如何删除有指针成员的类的指针?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的意思是,如果我有一些类像:
I mean, if i have some class like:
class A{
int* pi;
};
*A pa;
code> pi 被删除?
when i call delete pa
, will pi
be deleted?
推荐答案
您需要定义一个析构函数 delete pi;
。此外,您还需要定义一个复制构造函数和赋值运算符,否则当复制 A
的实例时,两个对象将指向同一个 int
,当 A
的一个实例被销毁而留下另一个 A
带有悬空指针。
You need to define a destructor to delete pi;
. In addition you also need to define a copy constructor and assignment operator otherwise when an instance of A
is copied two objects will be pointing to the same int
, which will be deleted when one of the instances of A
is destructed leaving the other instance of A
with a dangling pointer.
例如:
class A
{
public:
// Constructor.
A(int a_value) : pi(new int(a_value)) {}
// Destructor.
~A() { delete pi; }
// Copy constructor.
A(const A& a_in): pi(new int(*a_in.pi)) {}
// Assignment operator.
A& operator=(const A& a_in)
{
if (this != &a_in)
{
*pi = *a_in.pi;
}
return *this;
}
private:
int* pi;
};
这篇关于如何删除有指针成员的类的指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文