I list the steps / problems. They worked for me, but I cannot guarantee that they are 100% correct.
0) check if there can be cyclic common pointers. If so, could this lead to a memory leak? In my case, fortunately, loops should not be broken, because if I had a loop, the objects in the loop would be useful and should not be destroyed. use weak pointers to break loops
1) you need to replace "most" X*
with shared_ptr<X>
. Shared_ptr (only?) Created immediately after each dynamic distribution of X. In any case, this is a copy built or built with a null pointer (for a NULL signal). To be safe (but a little inefficient), pass these shared_ptrs by reference only. In any case, you probably never passed your pointers by reference to start with => no additional changes are required
2), you could use dynamic_cast<X*>(y)
in some places. replace this with dynamic_pointer_cast<X>(y)
3) where you passed NULL
(for example, to signal a calculation failure), pass an empty common pointer.
4) delete all removal instructions for the corresponding types
5) make your base class B inherited from enable_shared_from_this<B>
. Then, wherever you go, this
, go, shared_from_this()
. You may need to perform static casting if the function expects a derived type. keep in mind that when you call shared_from_this()
, some shared_ptr
should already have this
. In particular, do not call shared_from_this()
in the class constructor
I am sure that you can semi-automate this process to get semantically equivalent, but not necessarily very efficient code. The programmer probably only needs to talk about a circular reference (if any).
In many of these steps, I have repeatedly used regular expressions. It took about 3-4 hours. The code has compiled and executed correctly so far.