c++ - 数据类型不完整的容器的迭代器是否合法?

标签 c++ iterator incomplete-type

下面的代码合法吗?

class A
{
    std::map<int, A>::iterator x;
};

Visual Studio 2015 接受它,但 clang 说

.../ndk/sources/cxx-stl/llvm-libc++/libcxx/include/utility:254:9:  
error: field has incomplete type 'A'
    _T2 second;
    ^
....
a.cpp:52:21:
note: definition of 'A' is not complete until the closing '}'
    struct A
           ^

编辑:
问题似乎与标准库有关,http://rextester.com/QNNEG57036失败了

我的问题是代码是否合法,而不是如何修复它(例如通过更改编译器标志)。

最佳答案

除非在标准中明确声明不完全类型是合法的,否则它们是不合法的。具体部分是17.6.4.8 [res.on.functions] paragraph 2:

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.

我认为不需要任何容器来支持不完整的类型。一些智能指针确实允许不完整的类型。副手我想不出任何其他允许不完整类型的东西。快速搜索“不完整”会产生以下组件,允许不完整类型作为模板参数:

  • std::declval<T>()
  • std::unique_ptr<T>
  • std::default_delete<T>
  • std::shared_ptr<T>
  • std::weak_ptr<T>
  • std::enable_shared_from_this<T>

在代码示例中,std::map<int, A>::iterator实例化具有不完整类型的模板。因此,代码会导致未定义的行为。

关于c++ - 数据类型不完整的容器的迭代器是否合法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37767893/

相关文章:

c++ - VS2013 下的 emplace_back() 问题

c++ - 通过 C++ 为 AIR native 扩展生成可变长度的字节数组

c++ - 带三个参数的 std::move - 通过复制传递的迭代器

c++ - 创建一个 C++ 程序来处理电话线(固定电话)上的来电

c++ - C++中的双向选择排序

c++ - 如何在我的类(class)允许 range-for 循环?

c++ - iterator->second 是什么意思?

C++ - "Incomplete type not allowed"错误是什么意思,我该如何解决?

C++ 错误 : incomplete type used in nested name specifier

c - 错误: dereferencing pointer to incomplete type in main file