c++ - 使用和不使用新指针的区别

标签 c++ pointers stack new-operator

请引用这里给出的代码:

此代码是 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 nodenode* temp = new node;没有意义,因为temp是一次性赋值给top的。那么new node创建的原内存地址就丢失了,无法再次delete

Also does the memory automatically free itself or do I have to do it in destructor?

每个对象newed 都必须由您自己deleted。考虑一下smart pointers ,他们会为您管理这些事情。

关于c++ - 使用和不使用新指针的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40123927/

相关文章:

c++ - 使用 CMake 分发 Qt5 控制台应用程序

vba - 相当于 'this' 指针

c++ 字符串和指针混淆

c++ - 如何增加 Qt 中线程的堆栈大小 - QThread::setStackSize() 似乎不起作用?

java - 字符串相等,但 if 语句不触发

c++ - 我们真的需要将范围适配器隐式转换为 bool 值吗?

c++ - 捕获 boost 线程中断和退出线程的正确方法

C struct malloc 和指针数组实现

使用堆栈的 C 计算器。我想要这个计算器计算实数

c++ - 从基类调用重写的方法