map with incomplete value type

妖精的绣舞 提交于 2019-12-29 01:37:30

问题


I'm getting an error with the following:

class Test
{
    std::map<std::string,Test> test;
};

The error is "Field has incomplete type 'Test'". I read a few threads with suggested this might be a bug in the version of libcxx which ships with xcode, but it wouldn't surprise me at all if I just have to change it to:

class Test
{
    std::map<std::string,std::shared_ptr<Test>> test;
};

I just wanted to double check that this is definitely a correct error and not a bug.

Cheers!


回答1:


The standard requires that, all types used in template components of the standard library must be complete, unless otherwise stated. Thus libc++'s error is correct. Using an incomplete type is undefined behavior (§17.6.4.8[res.on.functions]/2), so libstdc++ accepting it isn't wrong either.

You could use a pointer object to construct the complete type as you did. But you could also use some third-party collections library which allows incomplete types, e.g. boost::container::map is designed to allow incomplete types.


§17.6.4.8 Other functions / 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.

(The only components that explicitly allow incomplete types are declval, unique_ptr, default_delete, shared_ptr, weak_ptr and enable_shared_from_this.)



来源:https://stackoverflow.com/questions/12281274/map-with-incomplete-value-type

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!