Home > Backend Development > C++ > body text

Can Incomplete Types Be Instantiated in Standard Containers?

Susan Sarandon
Release: 2024-11-05 22:56:02
Original
727 people have browsed it

Can Incomplete Types Be Instantiated in Standard Containers?

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!