代码之家  ›  专栏  ›  技术社区  ›  markzzz

为什么清除数据矢量后仍可以访问它?[副本]

  •  1
  • markzzz  · 技术社区  · 9 年前

    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 表示元素将被“销毁”,但它似乎并不意味着“默认/空”值。

    在其他语言中,我会在运行时收到“超出范围”的错误消息。。。

    2 回复  |  直到 9 年前
        1
  •  5
  •   songyuanyao    9 年前

    它似乎并不意味着“默认/空”值。

    是的,只是 UB .

    笔记 std::vector::operator[] 不执行边界检查,而 std::vector::at() 和类型为的异常 std::out_of_range 将被判入狱。

        2
  •  2
  •   Jens    9 年前

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

    在您的特定情况下,通过 std::vector::operator[] 是未定义的行为。编译器可以自由生成它想要的任何行为。常见的情况是执行对内存位置的访问并返回其中的内容。