std::vector operator[] 的不正确行为
Incorrect behavior of std::vector operator[]
我有下一个代码片段。这个想法是 vector 有 5 个项目,我通过 operator[] 访问 100 个项目,这应该会导致崩溃。但正如您在输出中看到的那样,它有效。
#include <vector>
#include <iostream>
int main() {
std::vector<int> vec(5, 1);
vec[100] = 25;
std::cout << "vec[100] = " << vec[100] << ", vec[99] = " << vec[99] <<
", vector size = " << vec.size() <<
", vector capacity = " << vec.capacity() << std::endl;
}
输出:
vec[100] = 25, vec[99] = 0, vector size = 5, vector capacity = 5
编译标志:
clang++ -W -Wall -std=c++14 -stdlib=libc++ vector_over_flow_test.cpp -o vector_overflow_test.bin
Clang 版本:
$clang++ --version
Apple LLVM version 8.0.0 (clang-800.0.42.1)
Target: x86_64-apple-darwin16.3.0
Thread model: posix
InstalledDir:
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin
Returns a reference to the element at specified location pos. No bounds checking is performed.
是否是实现中的错误?
which is supposed to lead to crash
没有。这只是 undefined behavior。这些实现不需要崩溃;一切皆有可能,包括看起来运作良好。请注意,您永远不应依赖它。
另一方面,std::vector::at 会执行边界检查,std::out_of_range
会在越界时抛出。
根据您引用的文档,这不是错误:
Returns a reference to the element at specified location pos. No bounds checking is performed.
幸好没有崩溃,正常工作。
我有下一个代码片段。这个想法是 vector 有 5 个项目,我通过 operator[] 访问 100 个项目,这应该会导致崩溃。但正如您在输出中看到的那样,它有效。
#include <vector>
#include <iostream>
int main() {
std::vector<int> vec(5, 1);
vec[100] = 25;
std::cout << "vec[100] = " << vec[100] << ", vec[99] = " << vec[99] <<
", vector size = " << vec.size() <<
", vector capacity = " << vec.capacity() << std::endl;
}
输出:
vec[100] = 25, vec[99] = 0, vector size = 5, vector capacity = 5
编译标志:
clang++ -W -Wall -std=c++14 -stdlib=libc++ vector_over_flow_test.cpp -o vector_overflow_test.bin
Clang 版本:
$clang++ --version
Apple LLVM version 8.0.0 (clang-800.0.42.1)
Target: x86_64-apple-darwin16.3.0
Thread model: posix
InstalledDir:
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin
Returns a reference to the element at specified location pos. No bounds checking is performed.
是否是实现中的错误?
which is supposed to lead to crash
没有。这只是 undefined behavior。这些实现不需要崩溃;一切皆有可能,包括看起来运作良好。请注意,您永远不应依赖它。
另一方面,std::vector::at 会执行边界检查,std::out_of_range
会在越界时抛出。
根据您引用的文档,这不是错误:
Returns a reference to the element at specified location pos. No bounds checking is performed.
幸好没有崩溃,正常工作。