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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With