使用和不使用新指针之间的区别

sam*_*joe 2 c++ stack pointers new-operator

请参考此处给出的代码:

此代码是C++中堆栈实现的一部分:

代码1:

void Stack::pop()
{
    if (top != 0) {
        node* temp = top;
        top = top -> link;
        delete temp;
    }
}
Run Code Online (Sandbox Code Playgroud)

代码2:

void Stack::pop()
{
    if (top != 0) {
        node* temp = new node;
        temp = top;
        top = top -> link;
        delete temp;
    }
}
Run Code Online (Sandbox Code Playgroud)

在第一个例子中,我没有使用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();
}
Run Code Online (Sandbox Code Playgroud)

在这里使用和不使用指针有什么区别

内存也会自动释放,或者我必须在析构函数中执行此操作吗?如果是这样,怎么办?

son*_*yao 5

第二个代码片段中存在内存泄漏,即使它看起来运行良好.new node没有意义node* temp = new node;,因为temp被立即分配top.然后创建的原始内存地址new node丢失,不能delete再次出现.

内存也会自动释放,或者我必须在析构函数中执行此操作吗?

每个对象new都必须delete由你自己完成.考虑一下智能指针,他们会为你管理这些事情.