How to create array of pointers in C++

2019-08-02 13:56发布

问题:

In class Node:

class Node {
public:
    int data;
    int numchild;  
    Node** nodelist;

    Node(int data, int s);
};

I want an array of pointers (nodelist) to other nodes, which have edges from this node.

Is the following way of constructing such an array (and the above way of declaring it) a correct and the best (or easiest) way possible? If not, why and whats the best way?

Node::Node(int d, int s) {
    data = d;
    numchild = s;
    nodelist = new Node*[s];
}

回答1:

Generally you shouldn't reinvent the wheel. Raw arrays are almost always the wrong way to go. Have a look at the various containers from the STL, i.e. std::vector, std::list. I woud guess that in your case a std::vector might be the best solution.

If you want to stick with the raw array, a quick warning: new Node*[s] does not initialize the array, so the contents will be undefined. But if you add a set of parentheses (new Node*[s]()) it will be initialized to zero which is a good thing as it helps you spot which entries have been filled already.

Also, your current code lacks a destructor to delete[] the nodelist again. That's exactly why the use of standard containers is recommended: they have destructors that will do the work for you.



回答2:

Well, if you insist, but the answer will neither be the best nor the easiest, and correctness is very much your burden now.

For the constructor, use the base initializer list:

Node::Node(int d, size_t s)
: data(d), numchild(s), nodelist(new Node*[s])
{
}

We also make numchild an unsigned type, since it represents a size.

But now you also have to take care to deallocate the memory on destruction. A simple delete[] won't do because you first have to traverse all the children and recursively deallocate their memory.

All in all, a vector of shared pointers would save you about 90% of the code.