下面的代码合法吗?
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/