C++ 中的递归容器?
最近我在查看一些代码,注意到类似于以下的数据结构:
class TreeNode {
std::vector<TreeNode> subNodes;
};
正如您所看到的,在定义 TreeNode 之前,容器是用 TreeNode 实例化的。该代码可以在 GCC 和 MSVC 下编译,但我记得看到有人说这不能保证行为。不幸的是,我在标准中找不到任何讨论这个问题的内容。
这样的容器如何实现?标准保证这种行为吗?如果标准不能保证这一点,我对此设计有哪些替代方案?
Possible Duplicate:
Are C++ recursive type definitions possible, in particular can I put a vector<T> within the definition of T ?
I was looking through some code recently and noticed a data structure similar to the following:
class TreeNode {
std::vector<TreeNode> subNodes;
};
As you can see, the container is instantiated with TreeNode before TreeNode has been defined. The code compiles under both GCC and MSVC, but I remember seeing something saying that this is not guaranteed behaviour. Unfortunately I can't find anything in the standard discussing this at all.
How are such containers able to be implemented? Is this behaviour guaranteed by the standard? If this is not guaranteed by the standard, what alternatives do I have to this design?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这很好,因为
std::vector
类中不包含任何T
类型的具体实例:它通常使用指针实现。模板实例化std::vector
不需要TreeNode
的完整定义。std::vector
通常作为指针三元组实现(尽管标准不要求这样做):If
std::vector
did 中是否包含T
的具体实例,那么您就会遇到问题。以下代码不是合法的 C++,因为它创建了一个循环“has a”定义:This is fine because the
std::vector<T>
class doesn't contain any concrete instances of the typeT
in it: it's typically implemented using pointers. The template instantiationstd::vector<TreeNode>
does not require the full definition ofTreeNode
.std::vector<T>
is usually implemented as a triplet of pointers (though this is not required by the standard):If
std::vector<T>
did contain concrete instances ofT
in it, then you would have a problem. The following is not legal C++, because it creates a circular "has a" definition: