Here代码:
vector<double> samples;
int main()
{
samples.resize(100);
for(int i=0; i<100; i++) {
samples[i]=i/100.0;
}
samples.clear();
cout << "vector size: " << samples.size() << endl;
cout << "... but samples[9]=" << samples[9] << endl;
}
输出它:
vector size: 0
... but samples[9]=0.09
清除向量(大小为0)后,我仍然可以访问其数据。这是正常的吗?
Reference表示元素将被“销毁”,但它似乎并不意味着“默认/空”值。
在其他语言中,我会在运行时收到“超出范围”错误消息...
答案 0 :(得分:5)
它似乎并不意味着“默认/空”值。
是的,它只是UB。
注意std::vector::operator[]
不执行边界检查,而std::vector::at()
则执行边界检查,并且将针对该情况抛出类型std::out_of_range
的异常。
答案 1 :(得分:2)
C ++与其他语言(如Java,C#或Python)不同,很多东西被定义为未定义的行为而不是产生错误,特别是检测它们的事情会产生运行时成本。检查数组的越界访问就是一个例子。未定义的行为,this also gives the compiler a great degree of freedom to optimize your code。
在特定情况下,通过std::vector::operator[]
进行的越界访问是未定义的行为。编译器可以自由地生成它想要的任何行为。常见的情况是执行对内存位置的访问并返回其中的内容。