0
#include <iostream>

struct Demo
{
    int a;
    int b;
};

int main()
{

    for(int i=0;i < 3; i++)
    {
        Demo d;
        d.a = i;
        std::cout  << "Reference of Demo " << &d << std::endl;
    }

    for(int i=0;i < 3; i++)
    {
        Demo d = {i};
        std::cout  << "Reference of Demo " << &d << std::endl;

    }
}

When i execute the above program getting the same reference in output

Reference of Demo 0x6dfef0

Reference of Demo 0x6dfef0

Reference of Demo 0x6dfef0

Reference of Demo 0x6dfee8

Reference of Demo 0x6dfee8

Reference of Demo 0x6dfee8

Can someone explain this behavior

SaiVikas
  • 144
  • 11
  • 1
    The compiler is allowed to re-use an address for objects who's lifetimes do not overlap. The compiler is *not required* to do this. It is equally valid for them all to be the same, or all to be different, or some other combination. – Caleth Feb 12 '19 at 09:43

1 Answers1

1

You create a Demo in the first loop. It is de-constructed, when the scope is left. In the second loop you create a new Demo, in a different location.

If you create the Demo before the loops you will get the same memory address shown in both loops.

#include <iostream>

struct Demo
{
    int a;
    int b;
};

int main()
{
    Demo d;
    for(int i=0;i < 3; i++)
    {
        d.a = i;
        std::cout  << "Reference of Demo " << &d << std::endl;
    }

    for(int i=0;i < 3; i++)
    {
        std::cout  << "Reference of Demo " << &d << std::endl;

    }
}
schorsch312
  • 5,032
  • 4
  • 21
  • 47
  • I understand for loop 1 and for loop 2 returning different references. My question was about getting same reference in loops. For loop 1 returns the same reference 3 times similarly for loop 2 returns same reference 3 times too.. – SaiVikas Feb 12 '19 at 07:51
  • There are two different objects `d` of the class `Demo`. One in the first loop, one in the second. Thus, they have different references. – schorsch312 Feb 12 '19 at 07:53