0

Consider the following program:

include <iostream>

using namespace std;

int main()
{

    int *ptr = new int(10);
    int &ref = *ptr;

    cout << ref << endl << &ref << endl;

    delete ptr;
    ptr = new int(100);
    cout << ref << endl << &ref << endl;

    return 0;
}

Output:
10
0x80010348
100
0x80010348

Here the ref variable is a reference to the memory location pointed by ptr. However, when the ptr pointer is deleted and a new memory location is assigned, ref should now be referring to an undefined memory location as the previous does not exist. But when I run this program I get the updated value and address through ref with g++ on cygwin/linux as well as VC++2012 express.

However, if ptr is not deleted, then ref is not updated, and the output shows the old value 10 and old address. Is this behavior standard or is it compiler specific? If it's standard then why the update of ref depends upon whether ptr is deleted or not?

sourav.d
  • 122
  • 7

1 Answers1

2

It's just the way the memory allocator happens to work. In your code:

delete ptr;
ptr = new int(100);

you delete one int and then you immediately ask for a new one. The runtime says "Fine, have this one. It was just made available".

Simple recycling.

Bo Persson
  • 90,663
  • 31
  • 146
  • 203