简体   繁体   English

是同一个memory分配给class的所有对象

[英]Is the same memory allocated to all objects of class

I was trying to build a linked list without allocating memory dynamically.我试图在不动态分配 memory 的情况下构建链表。 Note that I can build linked list using new operator.请注意,我可以使用 new 运算符构建链表。 The below code does not work.下面的代码不起作用。 When I debugged it I found out (as much as I can understand) that Node a(n, head) is allocated at the same address in the memory every time so the a stores pointer to itself.当我调试它时,我发现(据我所知) Node a(n, head)每次都分配在 memory 中的相同地址,因此a存储指向自身的指针。 If someone can explain to me, it would be of great help.如果有人可以向我解释,那将有很大帮助。

class Node {
public:
    int val;
    Node *next;
    
    Node(int n, Node *ptr = NULL) {
        val = n;
        next = ptr;
    }
};

class LinkList {
    Node *head = NULL;
public:
    void insertNode(int n) {
        Node a(n, head);
        head = &a;
    }
    void print() {
        Node* ptr = head;
        while (ptr != NULL) {
            cout << ptr->val << endl;
            ptr = ptr -> next;
        }
    }
};

int main() {
    LinkList a;
    a.insertNode(3);
    a.insertNode(4);
    a.print();
    return 0;
}

No, the same memory is not allocated to all objects of a class... but the same memory is allocated for the local variables of every function. Once a function returns, all its local variables are destroyed, so its local variable memory is now unused, and the next function call will use it for its local variables.不,同一个memory并没有分配给一个class的所有对象...但是同一个memory分配给每个function的局部变量。一旦function返回,它的所有局部变量都被销毁,所以它的局部变量88393388253未使用,下一个 function 调用将使用它作为局部变量。 Hence every time you call insertNode it uses the same memory to hold a .因此,每次调用insertNode时,它都使用相同的 memory 来保存a . And when you call print , it uses that same memory to hold ptr .当您调用print时,它使用相同的 memory 来保存ptr

This is just what usually happens.这正是通常发生的事情。 Not all compilers do it the same way, so you can't rely on it.并非所有编译器都以相同的方式执行此操作,因此您不能依赖它。 And if you had extra function calls between main and insertNode then insertNode 's variables wouldn't get the same addresses as they do when main calls insertNode directly.如果您在maininsertNode之间有额外的 function 调用,那么insertNode的变量将不会获得与main直接调用insertNode时相同的地址。

Also note that because you aren't allowed to use pointers to variables that were already destroyed, the optimizer is allowed to guess that when you use a pointer, it points to a variable that hasn't been destroyed, and sometimes this causes really weird behaviour.另请注意,因为您不允许使用指向已被销毁的变量的指针,所以允许优化器猜测当您使用指针时,它指向一个尚未被销毁的变量,有时这会导致非常奇怪行为。 So you mustn't use pointers to destroyed variables, ever, even if you would be okay with getting the wrong data.所以你永远不能使用指向被破坏变量的指针,即使你可以接受错误的数据。 The technical term is undefined behaviour .技术术语是未定义的行为

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

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