I have a list of pointers to objects where some of the objects contain a pointer to another object. When I remove an object in the list which has a linked object I need to remove them BOTH. I also want to position the next iterator at a convenient position which will usually be just after the object in the list which is to be deleted. Or if the linked item is next it will have to be just after the linked item.

There are peripheral issues such as why not using smart pointers etc. But this is just a simple demo - so please ignore lifecycle issues. I am looking for comments on the RemoveAllAssociated function.

This question appears to be off-topic. The users who voted to close gave this specific reason:

"Questions must involve real code that you own or maintain. Questions seeking an explanation of someone else's code are off-topic. Pseudocode, hypothetical code, or stub code should be replaced by a concrete example." – Jamal

1 Answer
1

OK. This is NOT C++ code. This is C that happens to use a few C++ features like std::list. I would call this "C with classes".

What you have failed to do is define the ownership of the pointers. Without ownership calling delete is a pain (because you don't know if calling delete is a good idea because you don't know the ownership).

There is no point in reviewing further until you define ownership semantics.
Who owns the pointer.

You have 6 RAW pointers. What happens if the constructor to B(3) throws an exception. Then you have just leaked a1/a2/a3. In modern C++ it is very rare to see RAW pointers. Pointers are usually contained inside an object (usually a smart pointer).

So now you have two people pointing at each object. So who is supposed to destroy them? You have not defined the ownership semantics thus we do not know who is responsible for deleting the pointers. Even worse if they are deleted via one method the other pointer points at an invalid location (as there is no feedback) between the pointers.

boost::ptr_list would hold and take ownership of the pointers very nicely.