使用STL容器向前声明对象 [英] Forward declaration of objects with STL containers
问题描述
考虑以下代码片段,其中第一行仅用作前向声明
Consider the following code snippet, where the first line serves only as forward declaration
class A;
接着定义新的班级
class B
{
vector<A> Av; //line 1
map<int, A> Am; //line 2
pair<int, A> Ap; //line 3
};
第1行和第2行使用前向声明似乎很好(这可能告诉我那些容器使用实现的指针类型),其中第3行似乎无法在VS2012上编译。
line 1 and line 2 seems to be fine with the forward declaration (which may tell me that those container use pointer type of implementation) where as line 3 does not seem to compile on VS2012.
我的问题是行为由标准或特定于我使用的编译器决定?
My question is that behavior dictated by the standard or specific to the compiler I am using?
谢谢
推荐答案
标准库类型的相关规则在[res.on.functions]中:
The relevant rules for the standard library types are in [res.on.functions]:
特别是,在以下情况下效果不确定:[...]实例化模板组件时,除非该组件专门允许,否则将不完整的类型(3.9)用作模板参数。
In particular, the effects are undefined in the following cases: [...] if an incomplete type (3.9) is used as a template argument when instantiating a template component, unless specifically allowed for that component.
vector<A> Av;
很好。允许使用不完整类型实例化 std :: vector
,只要它在使用任何成员之前就已完成即可。在[vector.overview]中的标准中有一个明确的例外:
is fine. std::vector
is allowed to be instantiated with an incomplete type, as long as it becomes complete before you use any of the members. There is an explicit exception for this in the standard in [vector.overview]:
不完整的类型
T <如果分配器满足分配器完整性
的要求17.6.3.5.1,则在实例化vector
时可以使用/ code>。T
应该在引用向量
的所得专业化的任何成员之前完成。
An incomplete type
T
may be used when instantiatingvector
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 :: list
和 std :: forward_list
有相似的措辞。
此:
map<int, A> Am;
格式错误。 std :: map
要求在实例化时按照第一个引号提供完整的类型。
is ill-formed. std::map
requires a complete type at point of instantiation as per the first quote. There is no exception for this container in the way that there is for vector
.
此:
pair<int, A> Ap;
不可能工作,因为对
是仅有两个成员的简单结构。为了拥有 A
类型的成员,您需要一个完整的类型。
cannot possibly ever work, since pair
is just a simply struct with two members. In order to have a member of type A
, you need a complete type.
这篇关于使用STL容器向前声明对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!