此代码适用于 linux。
#include <vector>
#include <iostream>
using namespace std;
int main ()
{
vector<int> v(10, 0);
cout << v[100];
return 0;
}
operator[] 用注释声明
// element access
/**
* @brief Subscript access to the data contained in the %vector.
* @param __n The index of the element for which data should be
* accessed.
* @return Read/write reference to data.
*
* This operator allows for easy, array-style, data access.
* Note that data access with this operator is unchecked and
* out_of_range lookups are not defined. (For checked lookups
* see at().)
*/
reference
operator[](size_type __n) _GLIBCXX_NOEXCEPT
{ return *(this->_M_impl._M_start + __n); }
但是 MSVS 编译器会警告此类下标超出范围的情况。有什么方法可以模仿它的行为吗?
最佳答案
其实,我的一个同事已经找到了想要的答案:
-D_GLIBCXX_DEBUG
标志激活 libstdc++ 的 Debug模式。
关于c++ - 如何在 Linux 上强制执行 vector 下标超出范围调试断言,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45104340/