[英]How can I declare a member vector of the same class?
Why on earth does the following piece of code work? 为什么以下代码有效呢?
struct A {
std::vector<A> subAs;
};
A is an incomplete type, right? A是不完整的类型,对吧? If there was a vector of A*s I would understand.
如果有一个A * s的矢量我会理解。 But here I don't understand how it works.
但在这里我不明白它是如何工作的。 It seems to be a recursive definition.
它似乎是一个递归的定义。
This paper was adopted into C++17 which allows incomplete types to be used in certain STL containers. 本文被C ++ 17采用,它允许在某些STL容器中使用不完整的类型。 Prior to that, it was Undefined Behavior.
在此之前,它是未定义的行为。 To quote from the paper:
引用该文件:
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
, andstd::forward_list
, as the first step.根据对Issaquah会议的讨论,我们达成了共识,即采用“不完全类型的容器”方法进行*,但将范围限制为
std::vector
,std::list
和std::forward_list
,第一步。
And as for the changes in the standard (emphasis mine): 至于标准的变化(强调我的):
An incomplete type
T
may be used when instantiatingvector
if the allocator satisfies the allocator-completeness-requirements (17.6.3.5.1).如果分配器满足分配器完整性要求 (17.6.3.5.1),则在实例化
vector
时可以使用不完整类型T
T shall be complete before any member of the resulting specialization of vector is referenced.在引用向量特化的任何成员之前, T应该是完整的。
So, there you have it, if you leave the default std::allocator<T>
in place when instantiating the std::vector<T, Allocator>
, then it will always work with an incomplete type T
according to the paper; 所以,你有它,如果在实例化
std::vector<T, Allocator>
时保留默认的std::allocator<T>
std::vector<T, Allocator>
,那么根据论文,它将始终使用不完整的类型T
; otherwise, it depends on your Allocator being instantiable with an incomplete type T
. 否则,它取决于您的分配器是否可以使用不完整类型
T
进行实例化。
A is an incomplete type, right?
A是不完整的类型,对吧? If there was a vector of A*s I would understand.
如果有一个A * s的矢量我会理解。 But here I don't understand how it works.
但在这里我不明白它是如何工作的。 It seems to be a recursive definition.
它似乎是一个递归的定义。
There is no recursion there. 那里没有递归。 In an extremely simplified form, it's similar to:
以极其简化的形式,它类似于:
class A{
A* subAs;
};
Technically, apart from size
, capacity
and possibly allocator
, std::vector
only needs to hold a pointer to a dynamic array of A
it manages via its allocator. 从技术上讲,除了
size
, capacity
和可能的allocator
, std::vector
只需要保存指向它通过其分配器管理的动态数组A
的指针。 (And the size of a pointer is known at compile time.) (并且在编译时已知指针的大小。)
So, an implementation may look like this: 因此,实现可能如下所示:
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;
};
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.