C++ 中的递归容器?

发布于 2024-11-17 21:52:25 字数 535 浏览 1 评论 0原文

可能的重复:
C++ 递归类型定义是否可行,特别是我可以将向量在 T 的定义范围内?

最近我在查看一些代码,注意到类似于以下的数据结构:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

那支青花 2024-11-24 21:52:25

这很好,因为 std::vector 类中不包含任何 T 类型的具体实例:它通常使用指针实现。模板实例化 std::vector 不需要 TreeNode 的完整定义。

std::vector 通常作为指针三元组实现(尽管标准不要求这样做):

template <typename T>
class vector
{
  ...
  T* start;
  T* end;
  T* end_of_storage;
};

If std::vector did 中是否包含 T 的具体实例,那么您就会遇到问题。以下代码不是合法的 C++,因为它创建了一个循环“has a”定义:

template <typename T>
class container
{
  T x;
};

class TreeNode
{
  container<TreeNode> subNodes;
};

This is fine because the std::vector<T> class doesn't contain any concrete instances of the type T in it: it's typically implemented using pointers. The template instantiation std::vector<TreeNode> does not require the full definition of TreeNode.

std::vector<T> is usually implemented as a triplet of pointers (though this is not required by the standard):

template <typename T>
class vector
{
  ...
  T* start;
  T* end;
  T* end_of_storage;
};

If std::vector<T> did contain concrete instances of T in it, then you would have a problem. The following is not legal C++, because it creates a circular "has a" definition:

template <typename T>
class container
{
  T x;
};

class TreeNode
{
  container<TreeNode> subNodes;
};
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文