我构建了一个自定义数据结构,类似于双向链接的 RBTree,虽然逻辑看起来不错,但我没有看到在删除节点时释放任何内存。
这是我的节点声明:
typedef struct rbtreere_node
{
public:
NMessage *n_message;
// Node Specific //
enum color color_ID; //<<--- Color for ID side of RBTreeRe
enum color color_Price; //<<--- Color for Price side of RBTreeRe
int id; //<<--- Unique Identifier.
rbtreere_node *left_ID, *right_ID, *parent_ID, *left_Price, *right_Price, *parent_Price;
}*node;
当我调用删除函数时,我在返回之前以 delete n
结尾。
我检查过,如果我在返回之前尝试访问任何 node n
数据,它仍然存在......
即我这样称呼:
delete n;
std::cout << n->color_ID<<"\n\n";
它确实返回了节点颜色
我应该为它构建一个自定义析构函数吗?
我也将 node message
作为 var 而不是指针,但这似乎没有改变任何东西......
编辑:我的问题是在删除任何甚至所有节点后,我没有看到内存使用量有任何下降。我应该以不同的方式处理它吗?
最佳答案
I checked and if I try to access any of the node n data before returning, it is still there...
delete n;
std::cout << n->color_ID<<"\n\n";
在删除后取消引用 n
具有未定义的行为。
Should I build a custom destructor for it?
没有。除非 n_message
拥有它指向的内存,在这种情况下,隐式析构函数会泄漏该内存。
My issue is that I do not see any drop in memory usage after deleting any or even all nodes.
malloc
的大多数实现(它通常用于new
的实现动态内存分配)从不将释放的内存返回给操作系统。相反,它将重新用于后续分配。这不是问题。
Should I handle it differently?
除了去掉有 UB 的“支票”,没有。一切似乎都符合预期。
关于C++ 指针结构不会被删除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41654618/