Search code examples
c++pointersmove

Does std::move invalidate pointers?


Assume the following:

template<typename Item>
class Pipeline
{
    [...]

    void connect(OutputSide<Item> first, InputSide<Item> second)
    {
        Queue<Item> queue;
        first.setOutputQueue(&queue);
        second.setInputQueue(&queue);
        queues.push_back(std::move(queue));
    }

    [...]

    std::vector<Queue<Item> > queues;
};

Will the pointers to queue still work in "first" and "second" after the move?


Solution

  • The pointers will not work, because queue is a local object which will be deleted at the end of connect. Even by using std::move you still create a new object at a new memory location. It will just try to use as much as possible from the "old" object.

    Additionally the whole thing will not work at all independent of using std::move as push_back possibly has to reallocate. Thus a call to connect may invalidate all your old pointers.

    A possible solution is creating Queue objects on the heap. The following suggestion uses C++11:

    #include <memory>
    
    template<typename Item>
    class Pipeline
    {
        [...]
    
        void connect(OutputSide<Item> first, InputSide<Item> second)
        {
            auto queue = std::make_shared<Queue<Item>>();
            first.setOutputQueue(queue);
            second.setInputQueue(queue);
            queues.push_back(queue);
        }
    
        [...]
    
        std::vector<std::shared_ptr<Queue<Item>>> queues;
    };