为什么不vector :: clear从向量中删除元素? [英] Why doesn't vector::clear remove elements from a vector?
问题描述
当我在 std :: vector
上使用 clear()
时,应该销毁所有元素
When I use clear()
on a std::vector
, it is supposed to destroy all the elements in the vector
, but instead it doesn't.
示例代码:
vector<double> temp1(4);
cout << temp1.size() << std::endl;
temp1.clear();
cout << temp1.size() << std::endl;
temp1[2] = 343.5; // I should get segmentation fault here ....
cout << "Printing..... " << temp1[2] << endl;
cout << temp1.size() << std::endl;
现在,我应该在尝试访问已清除向量时得到分段错误,
Now, I should have gotten segmentation fault while trying to access the cleared vector, but instead it fills in the value there (which according to me is very buggy)
结果如下:
4
0
Printing..... 343.5
0
这是正常吗?
推荐答案
当你访问的边界外时,一个向量,你会得到未定义的行为。这意味着任何事情都会发生任何东西。
When you access outside of the bounds of a vector, you get Undefined Behavior. That means anything can happen. Anything.
所以你可以得到旧的值,垃圾或seg错误。
So you could get the old value, garbage, or a seg-fault. You can't depend on anything.
如果要进行边界检查,请使用 at()
成员函数 operator []
。它将抛出异常而不是调用未定义的行为。
If you want bounds checking, use the at()
member function instead of operator []
. It will throw an exception instead of invoking Undefined Behavior.
这篇关于为什么不vector :: clear从向量中删除元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!