我已经使用c++中的链接列表构建了一个堆栈,但是有人告诉我,整个事情一文不值,因为我的析构函数不能有效地完成其工作,所以有人可以告诉我如何为该代码构建析构函数。据我了解,构造函数的工作是删除未使用的内存,我提到的析构函数还有其他功能吗?
任何帮助,将不胜感激。

#include <iostream>
#include <string>
#include <limits>
using namespace std;

class Stack
{
private:
    struct node
    {
        int data;
        node* next;

        node()
        {
          int data = 0;
          next = nullptr;
        }

    };
node* top;
public:
    Stack()
    {
        top = nullptr;
    }
    ~Stack()
    {
       delete top;
    }
 void push(int n)
 {
    node* temp = new node;
    temp->data = n;
    temp->next = top;
    top = temp;
 }

    int pop()
    {
        node* temp = top;
        top = top->next;
        return temp->data;
    }

    int peek()
    {
        return top-> data;
    }

    bool isEmpty()
    {
        return top == 0;
    }
};

int main()
{
    Stack stack;

    std::string command;

    while (true)
    {
        std::cout << "stack>";
        std::cin >> command;
        try
        {
            if (command == "pop")
            {
                if (stack.isEmpty())
                {
                    throw std::runtime_error("error: stack is empty");
                }
                 std::cout << stack.pop() << std::endl;
            }

            else if (command == "push")
            {
                int n;
                if (!(std::cin >> n))
                {
                    throw std::runtime_error("error: not a number");
                }
                stack.push(n);
            }

            else if (command == "peek")
            {
                if (stack.isEmpty())
                {
                     throw std::runtime_error("error: stack is empty");
                }
                std::cout << stack.peek() << std::endl;
            }

             else if (command == "end")
            {
                 while (!(stack.isEmpty()))
                 {
                    std::cout << stack.pop() << std::endl;
                 }
                return 0;
            }
            else
            {
                throw std::runtime_error("error: invalid command");
            }
        }
        catch (std::runtime_error& e)
        {
            std::cin.clear();
            std::cin.ignore(numeric_limits<streamsize>::max(), '\n');
            std::cerr << std::endl << e.what() << std::endl;
        }
    }
    return 0;
}

最佳答案

您在Stack::pop()方法中存在内存泄漏,并且Stack()析构函数仅删除top,因此,如果您有多个元素,则将发生另一次泄漏。处理动态分配的内存时,最好使用智能指针:

class Stack
{
    struct node;
    using node_ptr = std::unique_ptr<node>;
private:
    struct node
    {
        int data;
        node_ptr next;

        node(int n, node_ptr nxt) : data(n), next( std::move(nxt) )
        { // your old ctor has a bug, you "initialized" local variable
        }
    };

    node_ptr top;
    Stack() = default;
    ~Stack()
    {
         while(top)
             top = std::move( top->next );
    }

    int pop()
    {
       node_ptr temp = std::move(top);
       top = std::move(temp->next);
       return temp->data;
    }

    void push(int n)
    {
        top = std::make_unique<node>(n,std::move(top));
    }

    int peek() const
    {
        return top->data;
    }

    bool isEmpty() const
    {
       return !top;
    }
};

您的代码变得更小,更易于理解,并且没有以前的泄漏。您不必提供显式的Stack析构函数,但是效率低下(执行递归调用,但仍然正确)。提供的析构函数更加高效。

关于c++ - 链表中的C++析构函数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/52894735/

10-14 12:13
查看更多