Forward declaration of objects with STL containers

旧巷老猫 提交于 2019-12-01 17:13:16

The relevant rules for the standard library types are in [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.

This:

vector<A> Av;

is fine. std::vector is allowed to be instantiated with an incomplete type, as long as it becomes complete before you use any of the members. There is an explicit exception for this in the standard in [vector.overview]:

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.

There is similar wording for std::list and std::forward_list.

This:

map<int, A> Am;

is ill-formed. std::map requires a complete type at point of instantiation as per the first quote. There is no exception for this container in the way that there is for vector.

This:

pair<int, A> Ap;

cannot possibly ever work, since pair is just a simply struct with two members. In order to have a member of type A, you need a complete type.

[As supplemental instruction to Barry's answer]

According to the standard (C++17), only std::vector, std::list and std::forward_list could be used with incomplete type when instantiating.

§23.3.11.1/3 Class template vector overview [vector.overview]:

An incomplete type T may be used when instantiating vector if the allocator satisfies the allocator completeness requirements [allocator.requirements.completeness]. T shall be complete before any member of the resulting specialization of vector is referenced.

§23.3.9.1/4 Class template forward_list overview [forwardlist.overview]:

An incomplete type T may be used when instantiating forward_list if the allocator satisfies the allocator completeness requirements [allocator.requirements.completeness]. T shall be complete before any member of the resulting specialization of forward_list is referenced.

§23.3.10.1/3 Class template list overview [list.overview]:

An incomplete type T may be used when instantiating list if the allocator satisfies the allocator completeness requirements [allocator.requirements.completeness]. T shall be complete before any member of the resulting specialization of list is referenced.

Nope, this behavior is expected and standard.

The rational is that std::pair actually forms a struct, therefore both its types must be complete before instantiation.

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