由买买提看人间百态

boards

本页内容为未名空间相应帖子的节选和存档,一周内的贴子最多显示50字,超过一周显示500字 访问原贴
JobHunting版 - 请教一个C++问题
相关主题
一道fb的题,clone a graphLowest Common Ancestor of multiple nodes in a binary tree
问tree的iterative traversalleetcode上的populate next node I and II
Zenefits Onsite 一题讨论delete a node in linked list
请教如何实现图的数据结构C++问题在哪儿啊 kth Node of BST,大家帮忙
问一个Linkedin经典题recovery BST 不考虑相同值的情况么?
Lowest Common Ancestor回馈本版,新鲜店面,新题新气象
判断BT是否BST?热腾腾的 LinkedIn 电面题攒RP
Twitter电面未通过一道google面试题
相关话题的讨论汇总
话题: node话题: destructor话题: vector话题: delete话题: root
进入JobHunting版参与讨论
1 (共1页)
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 的大作中提到】
: 你这个vector里的指针怎么办?有其他地方有备份可以之后再delete还是就这样丢了?
: 如果就这样丢了的话那肯定有内存泄露

s*****n
发帖数: 5488
6
应该不会。

【在 K******g 的大作中提到】
: struct Node
: {
: int value;
: std::vector children;
: Node()
: {
: value = 0;
: };
: };
: 在一个函数里代码里,我先 Node* root= new Node;, 经过一系列处理后,然后

1 (共1页)
进入JobHunting版参与讨论
相关主题
一道google面试题问一个Linkedin经典题
Amazon 打印给定node距离最近的K个nodesLowest Common Ancestor
如何删除 linked list 的最后一个元素 (转载)判断BT是否BST?
问一个C++ delete 节点的问题Twitter电面未通过
一道fb的题,clone a graphLowest Common Ancestor of multiple nodes in a binary tree
问tree的iterative traversalleetcode上的populate next node I and II
Zenefits Onsite 一题讨论delete a node in linked list
请教如何实现图的数据结构C++问题在哪儿啊 kth Node of BST,大家帮忙
相关话题的讨论汇总
话题: node话题: destructor话题: vector话题: delete话题: root