请引用这里给出的代码:
此代码是 C++ 中堆栈实现的一部分:
代码 1:
void Stack::pop()
{
if (top != 0) {
node* temp = top;
top = top -> link;
delete temp;
}
}
代码 2:
void Stack::pop()
{
if (top != 0) {
node* temp = new node;
temp = top;
top = top -> link;
delete temp;
}
}
在第一个示例中,我没有使用 new,而在第二个示例中我确实使用了它。在运行时,两者都给出与完整程序相同的输出,可以在下面找到:
#include <iostream>
using namespace std;
struct node {
string name;
node* link;
};
class Stack
{
node* top;
public:
Stack();
void push(string s);
void pop();
void display();
~Stack(){}
};
Stack::Stack() {
top = 0;
}
void Stack::push(string s)
{
node* temp = new node;
temp -> name = s;
temp -> link = top;
top = temp;
}
void Stack::pop() // Function in question
{
if (top != 0) {
node* temp = new node;
temp = top;
top = top -> link;
delete temp;
}
}
void Stack::display()
{
node* temp = new node;
temp = top;
while (temp != 0)
{
cout << temp -> name << "\n";
temp = temp -> link;
}
}
int main() {
Stack s;
s.push("Ra");
s.push("Sa");
s.push("Ga");
s.pop();
s.display();
}
这里使用和不使用 new 指针有什么区别?
此外,内存是自动释放还是我必须在析构函数中释放?如果可以,怎么做?
最佳答案
第二个代码片段中存在内存泄漏,尽管它看起来运行良好。 new node
对node* temp = new node;
没有意义,因为temp
是一次性赋值给top
的。那么new node
创建的原内存地址就丢失了,无法再次delete
Also does the memory automatically free itself or do I have to do it in destructor?
每个对象new
ed 都必须由您自己delete
d。考虑一下smart pointers ,他们会为您管理这些事情。
关于c++ - 使用和不使用新指针的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40123927/