3

In c++, We all know that this code is wrong:

class Node {
    public:
        Node node;
};

However, declaring a vector like this is right, WHY?

class Node {
    public:
        std::vector<Node> nodeVec;
};
skyline09
  • 129
  • 1
  • 6
  • 3
    It isn't right, it is actually undefined behaviour (whether is thould be this way or not is a different matter.) Boost has [some containers that allow you to do this](http://www.boost.org/doc/libs/1_55_0/doc/html/container/main_features.html#container.main_features.containers_of_incomplete_types). – juanchopanza Jul 17 '14 at 10:26
  • 1
    @juanchopanza Why isn't it right? Nodes are added to the vector dynamically. There's no infinite recursion here. – Neil Kirk Jul 17 '14 at 10:27
  • 1
    @NeilKirk No idea why, but the standard says so. IIRC there has been discussion about removing this restriction. I don't know what the status of that is. – juanchopanza Jul 17 '14 at 10:28
  • It seems that [this site](http://www.drdobbs.com/the-standard-librarian-containers-of-inc/184403814) explain it, although I don't understand it.. – ikh Jul 17 '14 at 11:22
  • 2
    To address the logical issue; the first one can never work as it is infinite descent of Nodes. However in the second one, so long as the default constructor makes `nodeVec` empty there is no infinite descent. – M.M Jul 17 '14 at 13:55

1 Answers1

1

It works just fine in the C++14 compiler I'm using. And it provides a very convenient pattern for representing an arbitrarily large complex tree-shaped data structure inside a “single” instance. A nice property is that all storage management for the entire tree is handled automatically by std::vector. For example you can have a Node member variable in a class Foo and not worry about deleting the tree when you are done with the enclosing Foo instance.

As described elsewhere (How can I declare a member vector of the same class?) it is not a problem for the compiler because the size of std::vector<Node> itself is independent of the size of Node, because std::vector is a fixed size header with a pointer to a separate block of managed storage on the heap.

Craig Reynolds
  • 675
  • 7
  • 16