Deleting a dynamic array of pointers in C++

11,355

There are MANY solutions to this sort of problem, but the most obvious choice would be to change it to use

std::vector< std::shared_ptr<Node> >

Now you will have a reference counted pointer without writing any code, and an "array" that doesn't need to know it's predefined size.

You can of course implement a reference counted object within Node, or your own container object to do the same thing, but that seems like extra hassle for little or no benefit.

Share:
11,355
zawodny
Author by

zawodny

Updated on June 04, 2022

Comments

  • zawodny
    zawodny almost 2 years

    I have a question concerning deleting a dynamic array of pointers in C++. Let's imagine that we have a following situation:

    int n;
    scanf("%d", &n);
    Node **array1 = new Node*[n];
    /* ... */
    

    where Node is a certain structure defined beforehand. Suppose that after allocation with the new operator, we change the content of the array1 (but we do not delete anything!). What is the proper way to delete the array1 and all its content if there is a possibility of repeated pointers in the array (without sorting them or inserting into the set, in linear time)?