Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
707 views
in Technique[技术] by (71.8m points)

templates - Why C++ containers don't allow incomplete types?

Why doesn't C++ allow containers of incomplete types to be instantiated?

It's certainly possible to write containers that don't have this restriction -- boost::container is completely capable of doing this. As far as I can see, it doesn't seem to give any performance or other type of gain, and yet the standard declares it to be undefined behavior.

It does prevent recursive data structures from being built, for example.

Why then does the C++ standard impose this arbitrary restriction? What would have been the downside of allowing incomplete types as template parameters wherever possible?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Matt Austern, the chair of the C++ standardization committee's library working group, explained this decision of the committee in his Dr. Dobb's article by historical reasons:

We discovered, with more testing, that even the [simple] example didn't work with every STL implementation. In the end, it all seemed too murky and too poorly understood; the standardization committee didn't think there was any choice except to say that STL containers aren't supposed to work with incomplete types. For good measure, we applied that prohibition to the rest of the standard library too.

My understanding of this is that the committee did not want to invalidate existing implementations of the library by requiring them to support incomplete types retroactively.

In the same article he concedes that

In a future revision of C++, it might make sense to relax the restriction on instantiating standard library templates with incomplete types.

Given that the article dates back to 2002, and the prohibition remains in place in the current standard, I think that the decision of the boost designers not to wait for the future and build their own containers that allow incomplete types was fully justified.

Edit: See this answer for information on using incomplete types allowed by C++17 standard for some containers in the Standard C++ Library.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...