Although this is a very general question, here’s my specific example so you can understand what I’m asking.
I have a copy constructor for a quad-tree class. So I write a recursive helper method called copy so I can call it in my copy constructor. The helper takes one parameter, a node. The root node is given as the first argument when called from the constructor.
So now in my helper method, I create one new node call it newNode, and each node has member variables neChild, nwChild, seChild, swChild—-sw means southwest nw, ne, se are all cardinal directions, and I set each new child equal to that of source.child. Then I call the helper method again recursively on each source.child (4 of them). So this way, 1 node becomes 4, which then has 16 childs, and so on. And so then I return that first newNode I created.
Question:
Will that new returned node have all the other nodes attached to it? Will it be in a tree structure (although not formally a tree)? Or will those pointers attached to returned pointers go out of scope?
You will end up with a new root node which is linked to the same child nodes as the original tree. So any changes made to any children will affect both trees, and you may have a double-free problem later.
This is because, although you’re calling
copyrecursively, you’re discarding the return value.Furthermore, you said this
copyfunction is called from your copy constructor? You’re in for a world of hurt, becausecopycalls the copy constructor (at the return statement, since you return by value). That’s a recipe for a STACK OVERFLOW. I guess you’re in the right place 😉