Incomplete Type Instantiation in Standard Containers
In C , containers like std::vector and std::map allow the instantiation of containers with incomplete types. This practice was commonly used to create recursive structures through self-referential types. However, the C standard raises the question of whether such instantiations are permitted.
According to §17.6.4.8 of the C 11 standard, incomplete type instantiations can lead to undefined behavior if not explicitly allowed. Some containers, such as std::vector, work appropriately with incomplete types because they do not possess value_type members or functions that interact with value_type objects by value. However, std::map exhibits problematic behavior in this regard.
The standard's intent is to prohibit incomplete type instantiations, even if specific implementations may not encounter issues. This is primarily due to potential implementation difficulties, such as optimizing std::vector for a fixed number of elements, which could break if recursive structures were allowed.
Consequently, the standard mandates the use of complete types for container instantiation. However, it acknowledges the possibility of creating custom class templates that explicitly support incomplete types, as exemplified by std::unique_ptr.
As a result, standard containers should not be instantiated with incomplete types, though it is permissible to devise custom class templates that accommodate such usage.
The above is the detailed content of Can Incomplete Types Be Instantiated in Standard Containers?. For more information, please follow other related articles on the PHP Chinese website!