Return shared_ptr from function

I have a class that returns std :: shared_ptr aka Product_SPTR:

Product_SPTR Mill::Production(sf::Time time)
{
    if(m_isProducing)
    {
        if(elapsedTime.getElapsedTime()>m_manufacturingTime)
        {
            elapsedTime.restart();
            Flour_SPTR a(new Flour(5,1,ProductType::CONSTRUCTION),deleter<Flour>);
            return  a  ;

        }
    }

}

      

then i have typedef std::vector<Product_SPTR> VectorProduct_SPTR

and when I try to add a new Product_SPTR to the vector I have segmentation fault

Here:

products.push_back(a->Production(gameTime.getElapsedTime()));

      

But when I do something like this:

products.push_back(new Flour(5,1,ProductType::CONSTRUCTION),deleter<Flour>);

      

no problem arises ....

I have just started using smart pointers, so I may not know how to use it.

+3


source to share


1 answer


You missed a statement return

when conditions in if

are evaluated before false

. It compiles, probably gives you compiler warnings. You should always work at the highest warning level and eliminate all warnings one by one if you do not understand the warning and its consequences.

Additionally, instead of writing

Flour_SPTR a(new Flour(5, 1, ProductType::CONSTRUCTION),deleter<Flour>);
return  a;

      

You should probably write



return Flour_SPTR(new Flour(5, 1, ProductType::CONSTRUCTION), deleter<Flour>);

      

Modern compilers should have no problem optimizing a redundant variable, but it is always helpful to help the compiler get the job done. If you can skip the debater, you can also write:

return std::make_shared<Flour>(5, 1, ProductType::CONSTRUCTION);

      

+1


source







All Articles