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

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

问题描述

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

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

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

解决方案

这不是别人建议的实现中的错误。



违反C ++标准库设施的要求不会导致您的程序不成形,它会产生未定义的行为。



您违反了存储在容器中的值类型必须是可复制构造和赋值的要求( const types是不可分配的,显然),所以你的程序展现未定义的行为。



C ++标准中的适用语言可以在C ++ 03 17.4.3.6 [lib。在某些情况下(替换函数,处理程序函数,用于实例化标准库模板组件的类型的操作):



< ,C ++标准库取决于由C ++程序提供的组件。如果这些组件不满足其要求,则该标准对实施没有要求。



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



...




  • 用于在实例化模板组件时用作模板参数的类型对类型不实现适用的要求子句的语义。


Visual C ++标准库实现可以对此代码执行任何操作,包括静默删除或忽略const限定,它仍然符合标准。


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;

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.

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

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.

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

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:

...

  • for types used as template arguments when instantiating a template component, if the operations on the type do not implement the semantics of the applicable Requirements subclause.

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天全站免登陆