Function parameter - pointer or pointer reference?

void DeleteChildren(BSTNode *node)
{
    // Recurse left down the tree...
    if(node->HasLeftChild()) DeleteChildren(node->GetLeftChild());
    // Recurse right down the tree...
    if(node->HasRightChild()) DeleteChildren(node->GetRightChild());

    // Clean up the data at this node.
    node->ClearData(); // assume deletes internal data

    // Free memory used by the node itself.
    delete node;
}

// Call this from external code.
DeleteChildren(rootNode);

This function recursively deletes the BST.

I have a question about the first line, BSTNode *nodeshould I change it how BSTNode *& node?

+3
source share
4 answers

No, pointers are passed by value, so you essentially “copy” the pointer when you pass it as a parameter. Follow the link only if you want the caller to cause a parameter change in the caller.

+2
source

The only time you want to pass a pointer by reference is if you want to change what the pointer points to. If you want, for example, to install nodes on NULLafter removing them, you will need to go through how BSTNode*&.

+3

. , DeleteChildren, , rootNode .

Your parameter may be of type BSTNode * & if you need to change the address stored by rootNode. In this case, you do not.

0
source

No. Assuming that rootNodealso has type BSTNode*both rootNodeand nodepoint to the same memory location.

0
source

Source: https://habr.com/ru/post/1793084/


All Articles