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.