如何声明相同 class 的成员向量?

How can I declare a member vector of the same class?

到底为什么下面这段代码可以工作?

struct A {
    std::vector<A> subAs;
};

A 是一个不完整的类型,对吧?如果有一个 A*s 的向量,我会理解的。但是在这里我不明白它是如何工作的。好像是递归定义的。

paper was adopted 允许在某些 STL 容器中使用不完整的类型。在此之前,它是未定义的行为。引用论文:

Based on the discussion on the Issaquah meeting, we achieved the consensus to proceed* with the approach – “Containers of Incomplete Types”, but limit the scope to std::vector, std::list, and std::forward_list, as the first step.

关于标准的变化(强调我的):

An incomplete type T may be used when instantiating vector if the allocator satisfies the allocator-completeness-requirements (17.6.3.5.1). T shall be complete before any member of the resulting specialization of vector is referenced.

所以,你知道了,如果在实例化 std::vector<T, Allocator> 时保留默认值 std::allocator<T>,那么它将始终使用不完整的类型 T纸;否则,这取决于您的 Allocator 是否可以使用不完整的类型实例化 T.


A is an incomplete type, right? If there was a vector of A*s I would understand. But here I don't understand how it works. It seems to be a recursive definition.

那里没有递归。在极其简化的形式中,它类似于:

class A{
    A* subAs;
};

技术上,除了sizecapacity和可能的allocatorstd::vector只需要保存一个指向A的动态数组的指针通过其分配器进行管理。 (指针的大小在编译时是已知的。)

因此,实现可能如下所示:

namespace std{

    template<typename T, typename Allocator = std::allocator<T>>
    class vector{

        ....

        std::size_t m_capacity;
        std::size_t m_size;
        Allocator m_allocator;
        T* m_data;
    };

}