I have a question about new and delete:
Should I use delete for the input parameter or member object, e.g.:
https://github.com/jwbecalm/Head-First-Design-Patterns-in-CPP/blob/main/ch01_Strategy/main.cpp
Should I use delete on the object allocated by new FlyNewWay()?
// change behavior in runtime
mallardDuck->setFlyBehavior(new FlyNewWay());
// create custom MallarDuck on stack.
MallarDuck rocketDuck = MallarDuck(new FlyWthRocket(), new NewQuack());
and in MallardDuck constructor:
https://github.com/jwbecalm/Head-First-Design-Patterns-in-CPP/blob/main/ch01_Strategy/MallarDuck.cpp
MallarDuck:: MallarDuck(){
cout << "in MallarDuck:: MallarDuck()" << endl;
// 为MallarDuck 赋值其特有的行为
m_flyBehavior = new FlyWithWings();
m_quackBehavior = new SimpleQuack();
}
SHould I use delete to free m_flyBehavior and m_quackBehavior? but these two are members of object.
I can easily add delete in destructor of MallarDuck.
MallarDuck::~MallarDuck(){
cout << "in ~MallarDuck()" << endl;
delete m_flyBehavior;
delete m_quackBehavior;
}
but how about the input parameter mentioned in the first code block? or is this way to design and pass value not recommended? do you have some suggestions?
the setFlyBehavior() is as follows, if I add delete fb, it will delete m_flyBehavior also for my understanding because both fb and m_flyBehavior point to the same memory address.
void Duck::setFlyBehavior(FlyBehavior* fb){
m_flyBehavior = fb;
cout << "in Duck::setFlyBehavior()" <<endl;
}
after the setFlyBehavior(), both fb and m_flyBehavior point to the same memory address. so in the deconstructor: ~MallarDuck(), if I delete m_flyBehavior, the input parameter fb where it point to will be free too. So, the delete in deconstructor ~MallarDuck() is enough. thx .