Why do STL-Datastructures need fully defined types

我只是一个虾纸丫 提交于 2020-01-14 09:05:30

问题


When looking for a solution to this question, I found the this thread on another forum, which says that the standard requires all template parameters to STL-Datastructure to be fully defined. This means producing a structure which stores elements of the it's own type within itself invokes undefined behavior. However as far as I can tell this is not caught for most pre-C++11 datastructure (i.e. std::vector, std::map etc.).

What actually could be the problem of using incomplete types within STL-Datastructures? Or more exactely what potential danger could the following code cause:

#include <stdint.h>
#include <map>

struct Test {
  std::map<uint32_t, Test> m_map1;
};

int main() {
  return 1;
}

Or is this one of those issues, where this code might not compile with some STL-Implementations, but if it does compile, you can be sure that it works?


回答1:


The short answer is: because the standard says so. More generally, depending on the implementation, and what each type and function does, instantiating a template may require a complete definition. The authors of the standard either didn't want to, or didn't have time to analyse and specify in detail in what cases they didn't want to require complete definitions, and settled for a blanket statement. Note too that when the standard was written, there was relatively little experience with STL, and one could be sure that there wasn't some clever optimization which would require an instance of the argument type within a class; rather than risk banning such an optimization, it seemed safer to require a complete type.




回答2:


At least one problem your compiler faces with incomplete types is that it might be unable to fully determine the size of your struct Test. And thus, how could some container internally instantiate a Test?

Actually, as James said, it depends on how the std::map template uses the second type parameter. As long as it doesn't use instances but Test pointers it should compile. But who can claim this for all STL- (or in general, Container-) implementations out there? As the STL is part of your compiler suite one potential danger is reducing the portability of your code.



来源:https://stackoverflow.com/questions/8473455/why-do-stl-datastructures-need-fully-defined-types

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