为什么将变量类型 p 声明为新类型而不是将其声明为类型 p?

Why declare a variable type p as new type instead of declare it just as type p?

以下是我正在分析的一段代码。我不明白为什么所有者的代码将 node-point 类型的变量声明为 *node p = new node,而不仅仅是将其声明为 *node p。在我看来,这两种方法都会导致相同的行为。我错了吗?如果是,为什么?

class Queue {
    private:
        node *front;
        node *rear;
    public:
        Queue();
        ~Queue();
        bool isEmpty();
        void enqueue(int);
        int dequeue();
        void display();

};
    
void Queue::display(){
    node *p = new node;
    p = front;
    if(front == NULL){
        cout<<"\nNothing to Display\n";
    }else{
        while(p!=NULL){
            cout<<endl<<p->info;
            p = p->next;
        }
        cout << endl;
    }
}

假设默认构造一个node没有副作用,那么无论你写node *p还是node *p = new node,程序的行为确实是一样的,因为p 在下一行重新分配。

但是,由于new node创建的对象永远不会被删除,所以Queue::display每次调用都会泄漏内存。您似乎在代码中发现了错误。它可能可以通过删除 new node 并将 p 初始化为 front 来修复,因为我怀疑作者并不真正知道他在做什么。

node *p = front;