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/