STL Queue Data Lifetime

S

Scott Kilpatrick

Maybe I'm going crazy here. I thought that a queue deletes its copied
elements when the queue is destructed. Can someone explain why the
following code works?
--------------------------
string *p;
{

queue<string> q;
string x = "hello";
q.push(x);
p = &q.front(); // p points to "hello" stored in the queue
cout << "p, *p: " << p << ", " << *p << endl;
q.pop(); // shouldn't this invalidate p?
cout << "p, *p: " << p << ", " << *p << endl;

}
// the queue is dead, why does this work?
cout << "p, *p: " << p << ", " << *p << endl;
 
G

Gianni Mariani

Scott said:
Maybe I'm going crazy here. I thought that a queue deletes its copied
elements when the queue is destructed. Can someone explain why the
following code works?

It may "work" but it is undefined. Consider yourself "lucky".

Here is another example ...

#include <queue>
#include <string>
#include <iostream>

using namespace std;

struct Stuff
{
Stuff( const string & ix )
: mx( ix )
{
}

~Stuff()
{
mx = mx + " : dead dead dead - you're just lucky if you see this";
}

string mx;
};

void f()
{
Stuff *p;
{

queue<Stuff> q;
string x = "hello";
q.push(x);
p = &q.front(); // p points to "hello" stored in the queue
cout << "p, *p: " << p << ", " << p->mx << endl;
q.pop(); // shouldn't this invalidate p?
cout << "p, *p: " << p << ", " << p->mx << endl;

}
// the queue is dead, why does this work?
cout << "p, *p: " << p << ", " << p->mx << endl;

}

int main()
{
f();
}
 
S

Scott Kilpatrick

Gianni said:
It may "work" but it is undefined. Consider yourself "lucky".

Ah, ok. I knew something was screwy there. I spent some time writing a
reference counting smart pointer and noticed this during testing. For a
while I thought I wasted my time!

Thanks,
Scott
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top