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

标签 c++ visual-c++ stl constants visual-c++-2008

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

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

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

最佳答案

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

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

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

可在 C++03 17.4.3.6 [lib.res.on.functions] 中找到适用于 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:

...

  • 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/39843887/

相关文章:

c++ - 我在 C++ 初学者中遇到了无限循环问题

c++ - 在处理时写入数据 block - 由于硬件限制是否存在收敛值?

c++ - 可以在一个文件中定义两个 `istream_iterator` 吗?

C++:即使使用 "this"关键字,参数声明也会隐藏类成员

c++ - x!=x 是实现 std::isnan() 的合法方式吗

c++ - 为什么使用 std::forward 禁用模板参数推导?

python - 从不同的目录调用多个 python 函数

c++ - 代码仅在调试时有效

c++ - 像函数类型一样使用 char* 可以吗?

c++ - C++Builders clang32 编译器可以使用 VS 库吗