我遇到以下错误:
class Test
{
std::map<std::string,Test> test;
};
错误是“字段的类型不完整‘Test’”。我阅读了一些主题,建议这可能是 xcode 附带的 libcxx 版本中的错误,但如果我只需将其更改为:
class Test
{
std::map<std::string,std::shared_ptr<Test>> test;
};
我只是想仔细检查这绝对是一个正确的错误,而不是一个错误。
干杯!
最佳答案
标准要求,除非另有说明,否则标准库模板组件中使用的所有类型都必须是完整的。因此 libc++ 的错误是正确的。使用不完整类型是未定义的行为 (§17.6.4.8[res.on.functions]/2),因此 libstdc++ 接受它也没有错。
您可以使用指针对象来构造完整的类型。但是您也可以使用一些允许不完整类型的第三方集合库,例如boost::container::map
是designed to allow incomplete types .
§17.6.4.8 其他功能/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.
(唯一明确允许不完整类型的组件是declval
、unique_ptr
、default_delete
、shared_ptr
、weak_ptr
和 enable_shared_from_this
。)
关于c++ - 具有不完整值类型的映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12281274/