3

I have Class which 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'm trying to add new Product_SPTR to 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>);

problem does not occur....

I have just started to use smart pointers so maybe i don't know how to use it ..

6
  • What is deleter? What does Mill::Production return when m_isProducing is false? Do you post complete code?
    – Slava
    Commented Sep 24, 2014 at 19:29
  • try to return by reference
    – Decipher
    Commented Sep 24, 2014 at 19:30
  • 4
    There's no return statement for when either of the two conditions fail. That is a cause for undefined behavior.
    – David G
    Commented Sep 24, 2014 at 19:31
  • No good question: Handle all warnings the compiler emits, or increase the warning level.
    – user2249683
    Commented Sep 24, 2014 at 19:35
  • Yes it was stupid;) return nullptr, and all problems go away.. Commented Sep 24, 2014 at 19:37

1 Answer 1

1

You missed a return statement when the conditions in both ifs evaluate to false. It compiles, probably giving you compiler warnings. You should always work on the highest warning level and eliminate all warnings one by one, unless you understand a warning and its implications.

Additionaly, instead of writing

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

You probably should write

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

Modern compilers shouldn't have any problems with optimizing out the redundant variable, but it's always good to help the compiler do it's job. If you could skip the deleter you could also write:

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.