How to make std::vector's operator[] compile doing bounds checking in DEBUG but not in RELEASE

前端 未结 5 2127
小鲜肉
小鲜肉 2020-11-27 05:55

I\'m using Visual Studio 2008.

I\'m aware that std::vector has bounds checking with the at() function and has undefined behaviour if you try to access something usin

5条回答
  •  遥遥无期
    2020-11-27 06:57

    I asked this too prematurely, but I'm posting the answer anyway so I'm sharing some knowledge.

    The stl implemented in Visual Studio already do bounds checking when compiling in Debug mode. This can be seen at the header:

    reference operator[](size_type _Pos)
            {   // subscript mutable sequence
    
     #if _HAS_ITERATOR_DEBUGGING
            if (size() <= _Pos)
                {
                _DEBUG_ERROR("vector subscript out of range");
                _SCL_SECURE_OUT_OF_RANGE;
                }
     #endif /* _HAS_ITERATOR_DEBUGGING */
            _SCL_SECURE_VALIDATE_RANGE(_Pos < size());
    
            return (*(_Myfirst + _Pos));
            }
    

    so there is the bounds checking for the vector class. I didn't look at other containers, but I'm confident that they have the same mechanism.

提交回复
热议问题