简体   繁体   中英

Am I deleting an object, or just its pointer

I'm implementing my own version of a queue for practice, but wondering if I'm correctly deleting elements correctly, in the "pop()" function.

I'm new to C++ and I'm unsure if I'm just deleting a pointer to the Node I'm trying to delete, instead of the actual node itself.

#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删除传递给它的指针所指向的对象。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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