Archived

This topic is now archived and is closed to further replies.

Daddy-O

STL Queues & memory

Recommended Posts

If i create an instance of an object in a function and push it onto a queue in that function. When the function returns and the object falls out of scope is the object in the queue still valid?? I suppose what i mean is that does the STL queue allocate it''s own new memory for objects put in it?? some relevant code ~~~~~~~~~~~~~~~~~~ typedef queue< Event > EventQueue; EventQueue OrderQueue; void GameObject::Order(DWORD theOrder, DWORD * orderData) { Event a; a.Build(theOrder, orderData); OrderQueue.push(a); } I think that is right and there won''t be any memory leaks, or invalid objects in the queue (dangling pointers?). but if... i did this instead typedef queue< Event* > EventQueue; then i would need to make sure that Event a; still existed at the correct memory address. right??

Share this post


Link to post
Share on other sites
Correct.

You first example stores Event objects. As long as Event objects copy correctly (a copy constructor is defined if necessary) you shouldn't run into any problems. The container maintains it own copy of the item.

The second example stores pointers to Event object. The container still maintains it's own copy of the item, but now that item is simply a pointer. The container has no control over what is pointed to or it's lifetime. So, if you did the following:


    
typedef queue<Event*> EventQueue;

EventQueue OrderQueue;

void GameObject::Order(DWORD theOrder, DWORD * orderData)
{
Event a;
a.Build(theOrder, orderData);
OrderQueue.push(&a);
}



the container would be left with a dangling pointer once the function ended. If you can, store Events rather than pointers to Events. You'll end up with fewer bugs and your code will likely be easier to maintain.

[edited by - Solo on March 2, 2003 3:02:46 PM]

Share this post


Link to post
Share on other sites