为什么清空后还能访问数据向量?

Why can I still access to data vector after clear it?

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 表示元素将是 "destroyed",但它似乎并不意味着 "default/empty" 值。

在其他语言中,我会在运行时收到 "out of range" 错误消息...

it seems it doesn't mean "default/empty" values.

是的,只是 UB

注意 std::vector::operator[] doesn't perform bounds checking, while std::vector::at() 确实如此,并且将为这种情况抛出类型 std::out_of_range 的异常。

C++ 与 Java、C# 或 Python 等其他语言不同,许多事情被定义为未定义的行为而不是产生错误,尤其是检测到它们的事情会产生相关的运行时成本.检查数组的越界访问就是这样一个例子。作为未定义的行为,this also gives the compiler a great degree of freedom to optimize your code.

在您的特定情况下,通过 std::vector::operator[] 进行的越界访问是未定义的行为。编译器可以自由生成它想要的任何行为。常见的情况只是执行对内存位置的访问和return那里有什么。