c++pointerscustom-object

Array of pointers holds the same value for all elements


I'm currently deep-diving into the way pointers work.

Something for me unexplainable happened when executing the following lines of code:

        std::vector<OptimizerPlanOperatorPtr> sources;
        for (const auto &source : sourceOperators){
            OptimizerPlanOperator planOperator = OptimizerPlanOperator(source);
            sources.push_back(static_cast<std::shared_ptr<OptimizerPlanOperator>(&planOperator));
        }

all sourceOperators differ, however when checking the elements of sources, they all point to the same OptimizerPlanOperator.

When I ran the debugger, I realized that in every loop step, all values of sources change to the recent value.

My assumption is, that I poorly initialized the pointer here which somehow results in the value the pointer refers to being overridden.

Can somebody show a solution or explain, what I did wrong here?


Solution

  • You are storing the location of an object whose lifetime ends with the current iteration and handing ownership of it to a shared_ptr. Both are problems that lead to undefined behaviour.

    Casting a pointer to std::shared_ptr does not automagically make the pointed-to object into a shared object and extend its lifetime, and it is equivalent to std::shared_ptr<OptimizerPlanOperator>(&planOperator).

    The simplest solution is to not do this stepwise but all at once:

    for (const auto &source : sourceOperators){
        sources.push_back(std::make_shared<OptimizerPlanOperator>(source));
    }