为什么地址一样?

dag*_*ood 1 c++ memory linked-list

为什么每次循环运行时 temp 的地址(在 main 的 while 循环中)都相同我试图插入一个链表然后显示然后输出中间元素但最初在显示它时运行了一个无限循环只显示第一个元素。在插入后打印地址和 llist.add_ele_to_beg(&temp); 它每次都打印相同的地址!为什么会这样?

#include<iostream>
#include <unistd.h>

using namespace std;

class LinkedList;
class Node
{
    private:
    Node* next;
    int value;
    friend class LinkedList;
    public:
    Node(int ele) // constructor - declared in private section 
    // to prevent other classes creating objects of this class, 
    // only this class can create the object
    {
        next = nullptr;
        value = ele;
    }
};

class LinkedList
{
    private:
    Node* head;
    public:
    LinkedList()
    {
        head = nullptr;
    }
    void add_ele_to_beg(Node *temp)
    {
        // Node *temp = new Node(); // dynamically alloctg Node object
        // temp->value = x;
        temp->next = this->head;
        this->head = temp;
    }
    void display()
    {
        Node *h = this->head;
        while(h)
        {
            cout << h << endl;
            cout << h->value << endl;
            h = h->next; 
            cout << h << endl;
            cout << h->value << endl;
            exit(0);
        }
    }
    int findMiddle()
    {
        Node *fast, *slow = this->head;
        if(!slow)
        {
            return -1;
        }
        if(!slow->next)
        {
            return slow->value;
        }
        if(!slow->next->next)
        {
            return slow->value;
        }
        // n > 2
        fast = head->next->next;

        while(1)
        {
            slow = slow->next;
            if(!fast->next)
            {
                if(!fast->next->next)
                {
                    fast = fast->next->next;
                }
                else
                {
                    break;
                }   
            }
            else
            {
                break;
            }  
        }
        return slow->value;
    }
};

int main()
{
    LinkedList llist;
    int n;
    cout << "enter n" << endl;
    cin >> n;
    // create a dummy node
    cout << "enter elements to be inserted in the beg" << endl;
    int ele;
    while(n--)
    {
        cin >> ele;
        Node temp(ele); // obj node created and ctor initialises
        llist.add_ele_to_beg(&temp); // sending address of node to make change to 
        cout << &temp << endl;
        // node (passing by reference)
    }

    llist.display();

    cout << llist.findMiddle();
    cout << endl;
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

Sla*_*ica 5

为什么每次循环运行时 temp 的地址(在 main 的 while 循环中)都相同

因为您获得地址的对象具有自动存储期限。这意味着对象生命周期在它创建的块结束时结束(在你的情况下是循环结束),之后你有悬空指针。由于在对象的生命周期结束后被认为是空闲的内存,编译器出于实际目的再次重用相同的内存(它没有必要,但它可以并且有意义)。

为了使其正常工作,您应该创建具有动态存储持续时间的对象,这意味着您可以控制对象的生命周期。您可以new为此使用运算符,但最好使用智能指针而不是原始指针并让它管理对象生命周期。在这种情况下,您应该使用std::make_uniquestd::make_shared取决于您想要的所有权类型。您可以在此处找到有关如何使用智能指针的 C++ 链表的详细信息