Can standard container templates be instantiated with incomplete types?

Here’s my attempt at an interpretation:

The standard simply says you mustn’t do this, even though any given concrete implementation may have no problem supporting such a construction. But imagine for example if someone wanted to write a “small vector” optimization by which a vector always contains space for, say, five elements. Immediately you’d be in trouble because you’d have a self-referential type. This would be a problem even if the vector employed some sort of static branching depending on the size of the value type.

Therefore, in order to not preclude implementations from including such constructions, the standard simply says that you must only use complete types. In other words, the fact that most containers only contain references or pointers to the value type is an implementation detail rather than a standard requirement.

Just to clarify this: if you define your own class template, it is perfectly possible to design it in such a way that it explicitly supports incomplete types. An example from the standard is std::unique_ptr, which is perfectly happy with the incomplete type parameter T[] (or even void).

Leave a Comment