VC++ 允许对 STL 容器使用 const 类型.为什么? [英] VC++ allows to use const types for STL containers. Why?

查看:19
本文介绍了VC++ 允许对 STL 容器使用 const 类型.为什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

STL 容器要求存储的值是可复制构造和可分配的.const T 显然不是任何 T 的可赋值类型,但我尝试使用它(只是出于好奇)并发现它可以编译,而且还表现为可赋值类型.

STL containers require the stored values to be copy constructible and assignable. const T is obviously not an assignable type for any T, but I tried to use it (just being curious) and found out that it compiles and, moreover, behaves as an assignable type.

vector<const int> v(1);
v[0] = 17;

这在 Visual Studio 2008 中成功运行并将 v[0] 分配给 17.

This successfully runs in Visual Studio 2008 and assigns v[0] to 17.

推荐答案

这不是其他人建议的实现中的错误.

This is not a bug in the implementation as others have suggested.

违反 C++ 标准库工具的要求不会使您的程序格式错误,而是会产生未定义的行为.

Violating the requirements of a C++ Standard Library facility does not render your program ill-formed, it yields undefined behavior.

您违反了存储在容器中的值类型必须是可复制构造和可分配的要求(const 类型显然不可分配),因此您的程序表现出未定义的行为.

You have violated the requirement that the value type stored in a container must be copy constructible and assignable (const types are not assignable, obviously), so your program exhibits undefined behavior.

C++ 标准中的适用语言可以在 C++03 17.4.3.6 [lib.res.on.functions] 中找到:

The applicable language from the C++ Standard can be found in C++03 17.4.3.6 [lib.res.on.functions]:

在某些情况下(替换函数、处理函数、对用于实例化标准库模板组件的类型的操作),C++ 标准库依赖于由 C++ 程序提供的组件.如果这些组件不满足他们的要求,则标准不会对实现提出要求.

In certain cases (replacement functions, handler functions, operations on types used to instantiate standard library template components), the C++ Standard Library depends on components supplied by a C++ program. If these components do not meet their requirements, the Standard places no requirements on the implementation.

特别是,在以下情况下效果未定义:

In particular, the effects are undefined in the following cases:

...

  • 对于在实例化模板组件时用作模板参数的类型,如果对类型的操作没有实现适用的需求子条款的语义.

Visual C++ 标准库实现可以对这段代码做任何事情,包括静默删除或忽略 const 限定,它仍然符合标准.

The Visual C++ Standard Library implementation may do anything with this code, including silently removing or ignoring the const-qualification, and it is still standards-conforming.

这篇关于VC++ 允许对 STL 容器使用 const 类型.为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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