K******g 发帖数: 1870 | 1 struct Node
{
int value;
std::vector children;
Node()
{
value = 0;
};
};
在一个函数里代码里,我先 Node* root= new Node;, 经过一系列处理后,然后
delete root;
请问这样会有问题吗?是不是在执行delete root;的时候,系统会自动的调用
children这个vector的deconstructor?请问有必要先把vector清空吗? |
y**i 发帖数: 1112 | 2 你这个vector里的指针怎么办?有其他地方有备份可以之后再delete还是就这样丢了?
如果就这样丢了的话那肯定有内存泄露 |
i**********e 发帖数: 1145 | 3 When the program executes the line:
delete root;
The Node's destructor will be called. Since you did not define a destructor,
the default destructor would not do anything for you. Of course, the vector
's destructor would be called automatically upon destruction of Node object.
(This is because vector is an object in C++). But this does not mean the
object's that's pointed by the vector of Nodes will be deleted.
You should implement your own destructor in the following way:
~Node() {
int sz = childs.size();
for (int i = 0; i < sz; i++) {
delete childs[i];
}
}
When you call delete root;
it will in turn calls delete childs[i] for each of its child. And each of
its child's child's destructor will also be called... and so on. Therefore,
all Nodes would be cleaned properly and there would no memory leaked.
一些常见面试题的答案与总结 -
http://www.ihas1337code.com |
i**********e 发帖数: 1145 | 4 This is a good reference if the above still puzzles you.
http://www.parashift.com/c++-faq-lite/dtors.html
You can put a printf() message in the destructor to better understand how it
's called (and also the order of the destructors are called).
一些常见面试题的答案与总结 -
http://www.ihas1337code.com |
K******g 发帖数: 1870 | 5 我问的是vector,至于vector里的指针,在delete root;之前就必须释放掉的。
这个问题挺简单的,但是今天我在写code的时候,纠缠了好一阵子。平时许多觉得理所
当然的问题,code的时候却发现挺绕的。
【在 y**i 的大作中提到】![](/moin_static193/solenoid/img/up.png) : 你这个vector里的指针怎么办?有其他地方有备份可以之后再delete还是就这样丢了? : 如果就这样丢了的话那肯定有内存泄露
|
s*****n 发帖数: 5488 | 6 应该不会。
【在 K******g 的大作中提到】![](/moin_static193/solenoid/img/up.png) : struct Node : { : int value; : std::vector children; : Node() : { : value = 0; : }; : }; : 在一个函数里代码里,我先 Node* root= new Node;, 经过一系列处理后,然后
|