为什么在不使用"new"的情况下创建对象?操作员获得相同的地址 [英] Why does the object created without using "new" operator gets the same address

查看:76
本文介绍了为什么在不使用"new"的情况下创建对象?操作员获得相同的地址的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通过此问题,一个回答说创建的对象在其作用域之外被破坏了,为了清楚地理解这个概念,我编写了以下代码:

Going through this question, one answer said the object created are destroyed outside their scope, To get this concept clearly I wrote the following code:

#include <iostream>

using namespace std;

struct Node{
    int val;
    Node *next;
    Node(int x) : val(x) , next(NULL){}
};

int main(){
    for(int i=0;i<10;i++){
        int someval = rand()%100;
        Node somenode = Node(someval);
        printf("Address for object %d is %p \n",i+1, &somenode);
    }
}

我得到以下输出:

Address for object 1 is 0x7ffc32ff26b0 
Address for object 2 is 0x7ffc32ff26b0 
Address for object 3 is 0x7ffc32ff26b0 
Address for object 4 is 0x7ffc32ff26b0 
Address for object 5 is 0x7ffc32ff26b0 
Address for object 6 is 0x7ffc32ff26b0 
Address for object 7 is 0x7ffc32ff26b0 
Address for object 8 is 0x7ffc32ff26b0 
Address for object 9 is 0x7ffc32ff26b0 
Address for object 10 is 0x7ffc32ff26b0 

我知道每次循环迭代并创建一个新对象时,每个对象都会被破坏;但是为什么所有人都有相同的地址.当我创建一个链表时,我发生了这个问题,我没有使用new运算符来创建对象,而是使用了相同的代码,并且该表始终指向同一节点,因此我陷入了无限循环.为什么将相同的地址分配给每个对象?

I understand that each object is destroyed every time the loop iterates and a new object is created; but why do all of them have the same address. This problem occurred to me when I was creating a linked list and I did not use the new operator to create the object instead just used the same code, and the list always pointed to the same node and I ran into an infinite loop. Why is the same address allocated to each object?

推荐答案

您继续在堆栈,然后将其删除(对象在每次循环迭代结束时超出范围,并在下一次迭代之前进行解构).因此,每次为对象分配空间时,堆栈顶部的地址都是相同的.

You keep creating the object on the top of the stack, and then removing it (the object goes out of scope at the end of each loop iteration, and is deconstructed before the next iteration). Thus, the address of the top of the stack is the same everytime you allocate space for the object.

如果删除循环并连续分配多个Node,则随着堆栈的增加,您将看到每个地址的不同地址.

If you remove the loop and allocate multiple Nodes in a row, you'll see different addresses for each as the stack grows.

这篇关于为什么在不使用"new"的情况下创建对象?操作员获得相同的地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆