c++ - 使用 STL 容器的对象的前向声明

标签 c++ visual-studio-2012 stl forward-declaration std-pair

考虑以下代码片段,其中第一行仅用作前向声明

 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 上编译。

我的问题是,行为是由标准规定的还是特定于我使用的编译器?

最佳答案

标准库类型的相关规则在[res.on.functions]中:

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] 中的标准对此有一个明确的异常(exception):

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::liststd::forward_list 有相似的措辞。

这个:

map<int, A> Am;

格式错误。 std::map 根据第一个引号在实例化时需要一个完整的类型。与 vector 一样,此容器也不异常(exception)。

这个:

pair<int, A> Ap;

不可能工作,因为 pair 只是一个有两个成员的简单结构。为了拥有 A 类型的成员,您需要一个完整的类型。

关于c++ - 使用 STL 容器的对象的前向声明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38898935/

相关文章:

c++ - 判断下面函数是否判断数组是否升序排列

c++ - 倒水,哪里出了问题?

c# - IIS Express 停止 Web 应用程序后立即关闭正在运行的站点

c++ - 我可以从 ifstream/ofstream 获取使用的文件名吗?

c++ - 使用递归 C++ 将字符串转换为整数

visual-studio-2012 - F5 在调试器中运行 Visual Studio 测试

c# - 在 c# 中获取有关未引用 System.XML 的编译错误,是的,正在引用 System.XML

c++ - STL 或 Boost 能否帮助按值对 map 进行排序?

c++ - 就地 union 排序 vector

c++ - STL for_each 提示参数列表