Menu

Memory leak doubt in Strategy pattern

Arun Saha
2011-07-18
2013-04-29
  • Arun Saha

    Arun Saha - 2011-07-18

    I have doubt that there is a memory leak in the strategy pattern example, both in Bronze and Silver. I may be mistaken too! Either way,  it will be nice if the doubt is clarified.

    The doubt is on the flyBehavior object in the objects of the classes (e.g. ModelDuck) inherited from Duck class.

    In ModelDuck.hpp:
    public: ModelDuck() {
    quackBehavior = new Quack();
    flyBehavior = new FlyNoWay();
    }

    In MiniDuckSimulator.cpp
    model.setFlyBehavior(new FlyRocketPowered());

    In Duck.hpp
    public: virtual void setFlyBehavior(FlyBehavior* fb) {
    flyBehavior = fb;     // The old pointer is lost here
    }

    Thanks and regards,
    Arun

     
  • gpuchtel

    gpuchtel - 2011-07-19

    Hi Arun. Yes it leaks memory. As you know, the 'Bronze' version is simply a syntax only implementation. That is, I simply took their examples and translated it verbatim in C++. The 'Silver' version is meant to be a semantic implementation that uses more C++ idioms; however, I can't say I did a complete job . Still, it’s a good catch and I hope to deliver a better 'Silver' version in the near future. Thanks for taking the time to post a comment.

     

Log in to post a comment.