I’ve got this small snippet:
Action* newAction(Agent& a, ACTION_MODE& m)
{
Action *new_action;
do
{
new_action = new Action(a,m);
}
while (!state->addAction(new_action));
return new_action;
}
state->addAction(Action *a); will return true if *a was added, false if *a not added (checks to see if *a already exists).
Now, I know that goto’s are considered evil from lots of people, so, In the above snippet, re-allocating new_action in every loop, without deleting it, isn’t that wrong ?
Wouldn’t the following snippet be more “sensible” ?
retry :
Action *new_action = new Action(a,m);
if (state->addAction(new_action))
{
return new_action;
}
else
{
delete new_action;
goto retry;
}
I’m sorry if this seems elementary but it is something I’ve wondered about for some time now. What is correct, to delete the memory and then re-allocate, or can I re-allocate instantly ?
EDIT:
Would that be better ?
Action* newAction(Agent& a, ACTION_MODE& m)
{
// state will only allow an action to be added if it does not already exist
Action *new_action = new Action(a,m);
if (!new_action) return 0;
while (!state->addAction(new_action))
{
delete new_action;
new_action = new Action(a,m);
}
return new_action;
}
The caller of this function expects a new action which has been already added to state, so therefore deletion must take place in here.
You have a potential memory leak in that code in that you are creating a new action every time through the loop but, if it fails to add, you don’t free it. Better would be to move the action creation outside of the loop with something like:
This is more efficient than continuously deleting and re-creating the action and should be used in preference.
I’ve also fixed the return type so that the compiler won’t complain, and you should probably introduce some sort of failure strategy if you are never able to add the action.
Something like: