开发者

Clarification on lists and removing elements

开发者 https://www.devze.com 2022-12-08 06:27 出处:网络
If I have a list<object*>>* queue and want to pop the first object in the list and hand it over to another part of the program, is it correct to use (sketchy code):

If I have a list<object*>>* queue and want to pop the first object in the list and hand it over to another part of the program, is it correct to use (sketchy code):

object* objPtr = queue->first();
queue->pop_first();
return objPtr;  // is this a pointe开发者_运维百科r to a valid memory address now?

?

According to the documentation on http://www.cplusplus.com/reference/stl/list/pop_front/ it calls the destructor of the deleted element, but I'm confused as to whether it means the linked list's node object, or the actually stored "user" object.

Edit: I might be front instead of first, my bad.


Yes, it is a valid pointer. List will not release the memory allocated by you. List will destroy its internal not the user object.


Yes it's valid: Since you put pointers into the list, only the pointer gets destroyed, not the object itself.


Yes objPtr contains pointer to a valid memory.

When you insert an element into a std::list, list makes a copy of it. In your case the element is an address (a pointer) so list makes a copy of the address and stores it.

object * optr = queue->pop_front();

optr now points to the object

queue->pop_front();

removes the element (an address/pointer) from the list, optr already points to your object.

After you're done with the object don't forget do delete it otherwise you end up with memory leak.

Example:

#include <iostream>
#include <list>

using namespace std;

struct A
{
    static int count;

    A() : val(count++) { cout << "A(" << val << ")" << endl; }
    ~A()               { cout << "~A(" << val << ")" << endl; }

    int val;
};

int A::count = 0;

ostream& operator<<(ostream& os, A& a) { return os << a.val; }

int main()
{
    list<A*> alist;

    for (unsigned int i = 3; i; --i) alist.push_back(new A());
    for (unsigned int i = 3; i; --i)
    {
        A * aptr = alist.front();
        alist.pop_front();
        cout << *aptr << endl;
        delete aptr;
        aptr = 0;
    }
}


The standard indeed says (23.2.2.3/5) that the destructor of the element's type is called. But this type is a pointer here, and the destructor of a pointer does nothing...


Your code is well but it is better to use list< boost::shared_ptr<object> >.


   shared_ptr < object> objPtr = queue->first();
   queue->pop_first();
   return objPtr;  


When you remove the elements, STL containers will not destroy the user objects allocated on heap.

class A
{

};


list<A*> PointerToObjectList;

A* ptr = new A();
PointerToObjectList.push_back(ptr);

If you remove the ptr from the list, list will not delete the object automatically. You need to explicitly call delete once the object is no longer being used.

0

精彩评论

暂无评论...
验证码 换一张
取 消