gpt4 book ai didi

c++ - VC++ 允许对 STL 容器使用 const 类型。为什么?

转载 作者:IT老高 更新时间:2023-10-28 23:17:36 25 4
gpt4 key购买 nike

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

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

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

最佳答案

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

违反 C++ 标准库设施的要求不会使您的程序格式错误,它会产生未定义的行为。

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

C++ 标准中适用的语言可以在 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.

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

关于c++ - VC++ 允许对 STL 容器使用 const 类型。为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4940419/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com