Well, for starters, this is not a copy constructor - copy constructors have very clearly defined syntax in C ++, so the corresponding copy constructor will have a prototype TreeNode(TreeNode const &) . Just to get the terminology correct (and the compiler will still generate the copy constructor, since it does not know what the clone() function should do).
The expression in the if statement will highlight the new TreeNode and verify that the selection is successful (by checking that the resulting pointer is not 0). Unfortunately, this standard version of C ++ and modern C ++ implementations, which corresponds to the standard, instead generates an exception std::bad_alloc , so the test will basically give the user a warm fuzzy feeling that something is happening with a memory allocation failure, even if itโsnโt
For the code to work properly on the standard compiler, you will have to use nothrow new. In memory, the line will read something like this:
if (TreeNode* tmp = new(std::nothrow) TreeNode)
All that said, if TreeNode is not part of the hierarchy of objects that relies on the presence of the clone() function, I would end it and implement my own C ++ constructor instead. Thus, the compiler and you are on the same page when it comes to duplicating objects, as well as other programmers will be a little easier to follow your code.
source share