【发布时间】:2018-04-09 23:58:24
【问题描述】:
我有一个名为 Linked number 的结构
struct LinkedNum{
int num;
LinkedNum * next;
}
然后我使用 new 运算符为这个结构分配动态内存。
LinkedNum * first;
first = new LinkedNum;
first->num = 10;
first->next = nullptr;
LinkedNum * base;
base = first;
base->next = new LinkedNum;
base = base->next;
base->num = 20;
base->next = nullptr;
现在我将如何释放这个结构使用的所有内存。有两个结构 1 有 num = 10,其他有 num = 20。 我想删除所有结构,这样就不会有内存泄漏和悬空指针。
提前谢谢...
【问题讨论】:
-
使用
std::unique_ptr<LinkedNum> next;,不用再担心了。 -
使用标准containers
-
把你在纸上的链表画出来,想一想。想想
first指向的地方。 -
不要像在 C 中那样编程。使用 C++ 特性,如构造函数和析构函数。
标签: c++ pointers struct dynamic-memory-allocation