有关删除运算符的问题 [英] Question on delete operator
问题描述
大家好,
我对delete []运算符有以下疑问.
想象一下我有两个班.
Hi people,
I have following question on delete [] operator.
Imagine I have two classes.
Class A
{
....
char * data;
~A() // destructor
{
if (data) delete [] data;
}
}
class B
{
A * objectA;
...
~B() // destructor
{
delete objectA;
}
void function()
{
// now imagine here I create a pointer to A object
objectA = new A;
objectA->data = new char [100];
}
}
我的问题是.想象
My question is. Imagine
funtion()
被调用了.然后我调用了B类析构函数-删除对象A的析构函数,这是否意味着指针-> data变量也将被删除? (即,以后我不需要单独
was called. And afterwards class B destructor was called - the one that deletes object A -- my question is, will this imply that pointer->data variable will also be deleted? (i.e., won''t I need to separately
delete [] data
了吗?-一旦
delete [] data
)
Thanks
is being called in this code)
thanks
推荐答案
在A的构造函数中将data
指针设置为0,就可以了.与您的B类和objectA相同.
在您的function
中,没有正在构造的B型对象.但假设您添加了一行
Set yourdata
pointer to 0 in the constructor of A and you will be fine. Same for your class B and objectA.
In yourfunction
, there is no object of type B being constructed. But let''s assume you added a line
B b;
b.objectA = new A;
然后,B的构造函数将删除A对象,该对象随后将调用A的析构函数.
顺便说一句,您似乎从未编译过代码. C ++中的关键字类用小写的c拼写.而且您需要在开头加上public:
行,否则您的成员变量将无法从外部代码访问.
Then the constructor of B would delete the A object, which in turn would call A''s destructor.
By the way, you seem not have compiled your code ever. The keyword class in C++ is spelled with a lower-case c. And you would need to a public:
line at the beginning, or your member variables will not be accessible from outside code.
您的代码无法编译.下面的代码确实并重现了运行时错误:
You code doesn''t compile. The following one does and reproduces the runtime error:
class A
{
//....
public:
char * data;
~A() // destructor
{
if (data) delete [] data;
}
};
class B
{
A* objectA;
public:
~B() // destructor
{
delete objectA;
}
public:
void function()
{
// now imagine here I create a pointer to A object
A * pointer = new A;
pointer->data = new char [100];
}
};
int main()
{
B b;
b.function();
}
您收到错误消息是因为:
You get an error because:
- 您永远不会为
objectA
分配内存,而是在B
的ctor中删除它. - 您永远不会初始化
objectA
的成员data
- You never allocate memory for
objectA
but you delete it insideB
''s ctor. - You never initialize the
objectA
''s memberdata
(注意:与pointer
临时变量有关的内存).
解决方法是
(note: memory associated to pointer
temporary variable leaks).
A fix would be
class A
{
public:
//..
A():data(NULL){}
//..
};
class B()
{
public:
//..
B():objectA(NULL){}
};
(如果您有更新的编译器,则可以使用nullptr
而不是NULL
)
总体而言,您的设计看起来并不十分坚固.
(you may use nullptr
instead of NULL
if you have an updated compiler)
On the overall your design doesn''t look terribly robust.
这篇关于有关删除运算符的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!