为什么STL-数据结构需要完全定义类型 [英] Why do STL-Datastructures need fully defined types

查看:145
本文介绍了为什么STL-数据结构需要完全定义类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在寻找此问题的解决方案时,我在其他论坛上发现了此主题,表示该标准要求所有模板参数对STL-数据结构进行完全定义。这意味着生成一个结构,它将自己类型的元素存储在自身中调用未定义的行为。但是,据我所知,这不是大多数前C ++ 11数据结构(即 std :: vector std :: map 等)。

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.).

在STL-Datastructures中使用不完全类型的问题究竟是什么?或者更准确地说,以下代码可能导致的潜在危险:

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?

推荐答案

简单的答案是:因为标准说。更一般地,
取决于实现,以及每个类型和函数,
实例化模板可能需要一个完整的定义。作者
的标准要么不想,要么没有时间分析
,并详细说明在什么情况下他们不想要完整的
定义,解决了一个全面的声明。还要注意,当
标准被编写时,对
STL有相对少的经验,并且可以确定没有一些聪明的优化
,这将需要一个参数的实例类内;
而不是风险禁止这样的优化,似乎更安全
需要一个完整的类型。

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.

这篇关于为什么STL-数据结构需要完全定义类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆