Search code examples
c++stl

How can I use element from deque::pop_front() safely?


I have two std::deque, I want to move elements from one to another like this:

    T* t = new T;
    q1.push_back(t);
    std::deque<T*> q2;
    q2.push_back(q1.front());
    q1.pop_front();

my question is:

1: Does pop_front() release memory? if so, q2 can not visit the element.

2: Will push_back(q1.front()) do Copy constructors or assignment constructors


Solution

  • No standard container is aware of the data you put into it.

    Therefore it can't use, process or otherwise manipulate the data it stores, only store it. So if you store a pointer, the deque can't release the objects that the pointers are pointing to, since it doesn't know it's a pointer to an object.

    So to answer your question: Yes it's safe to "move" the pointers from one container to another. The objects being pointed to will not be affected by copying or moving the pointer itself.