C++ std::queue::pop() calls destructor. What of pointer types?

前端 未结 3 615
滥情空心
滥情空心 2020-12-28 17:49

I have a std::queue that is wrapped as a templated class to make a thread-safe queue. I have two versions of this class: one that stores value types, one that s

3条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2020-12-28 18:28

    "How do I ensure that everything is being removed and the memory deallocation properly?"

    If you absolutely have to store pointers in your queue, and you want them to be automatically freed when they're poped, then instead of a queue of pointers, you need a queue of objects which store a pointer, and delete it in their destructor. You could for example use a queue of shared_ptr. shared_ptr isn't in the standard library, but it's part of TR1 and is widely available.

    Otherwise, it's the responsibility of the caller to delete the object:

    T *off = q.front();
    q.pop();
    delete off;
    

    The summary is that containers of pointers to dynamically allocated objects are a bit awkward. If you can design your program so that containers store copies of your objects, instead of pointers to dynamic objects, then do so. Failing that, you're responsible for resource ownership, not the container. STL containers know nothing about ownership, they just copy and destroy their value_type. Copying and destroying pointers does nothing to the objects they point to.

提交回复
热议问题