繁体   English   中英

我是删除一个对象,还是只是它的指针

[英]Am I deleting an object, or just its pointer

我正在实现我自己的队列版本以供练习,但想知道我是否在“pop()”函数中正确删除了元素。

我是 C++ 的新手,我不确定我是否只是删除指向我要删除的节点的指针,而不是实际节点本身。

#include <iostream>

template <typename T>
class Queue {
    struct Node {
        Node* next;
        Node* previous;
        T data;
        Node(T value){
            next = nullptr;
            previous = nullptr;
            data = value;
        }
    };

    Node* front;
    Node* back;

    public:
        Queue(){
            front = nullptr;
            back = nullptr;
        }

        void push_back(T data){
            Node* n = new Node(data);
            if(front == nullptr){
                front = n;
                back = n;
            } else {
                back->next = n;
                back = n;
            }
        }

        void print(){
            Node* cursor = front;
            while(cursor != nullptr){
                std::cout << cursor->data << '\n';
                cursor = cursor->next;
            }
        }

        T pop(){
            Node* temp = front;
            T element = temp->data;
            front = front->next;
            delete temp; // Is this deleting the pointer or the Node it points to?
            return element;
        }
};

int main(){
    Queue<int> q;
    q.push_back(1);
    q.push_back(2);
    q.push_back(3);
    q.print();
    int element = q.pop();
    q.print();
}

delete删除传递给它的指针所指向的对象。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM