does pop( ) method delete the object from the memory?

Viewed 224

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 !

1 Answers

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.

Related