2

In the following code:

#include<iostream>
#include<queue>
using namespace std;
int main()
{
    queue<int> q;
    int a = 5;
    q.push(a);
    cout << q.front() << endl;    // 5
    int* b = &(q.front());
    q.pop();
    cout << *b;          // Outputs 5 but why ?
}

Is a copy of 'a' created inside the queue when I pass 'a' into it ? And when I pop out 'a', then why I am able to dereference the pointer to get the correct output i.e. 5. All I know is that pop() calls the destructor .

Please help !

dd3012
  • 53
  • 7
  • The b pointer points to junk. An int "destructor" wouldn't bother zeroing its contents. If you look at q.size(), you'll find that it is empty. – Captain Giraffe Feb 08 '22 at 10:23
  • 4
    Yes, it destroys the element. Accessing the pointer afterwards causes [_undefined behavior_](https://stackoverflow.com/questions/2397984/undefined-unspecified-and-implementation-defined-behavior), which means that you have _no guarantee_ on how the program will behave. It seemingly working is one possible manifestation of undefined behavior, but it may not the next time you compile or run the program. – user17732522 Feb 08 '22 at 10:25
  • 1
    As the old saying goes, undefined behaviour is undefined. That your output appears to be correct is just bad luck. – molbdnilo Feb 08 '22 at 10:25

1 Answers1

0

Calling the destructor means that the object is destroyed and the program is no longer using it. It doesn't mean that the memory it took is now overwritten. So, in short:

  • The object data might still be in memory as garbage.
  • So the contents of the same memory address will depend on whether the program has already used that memory for something else or not.

As the behaviour of accessing garbage data is undefined, this might vary between executions.

Miguel
  • 2,130
  • 1
  • 11
  • 26