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;
};
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;
};
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.