自动检查std :: vector中的边界 [英] Automatically check bounds in std::vector
问题描述
在积极开发使用 std :: vector
的类的过程中,经常会发生索引超出范围的情况。 (有关实际示例,请参见此代码审查问题。)使用 operator []
,这将导致未定义的行为。不过,与编写 .at()
相比, []
语法更易于阅读,更方便。
因此,我想使用 []
运算符编写代码,但同时启用了边界检查。测试代码后,应该很容易删除边界检查。
我在考虑以下代码:
util :: bound_checked< std :: vector< int>>数字;
个数字.push_back(1);
数字.push_back(2);
数字.push_back(3);
数字.push_back(4);
std :: cout<<数字[17]<< \n;
对我来说,此实用程序模板非常简单明了,以至于我希望它存在。可以?如果是这样,用什么名字命名?
对我来说,这个实用程序模板似乎很简单-向前,我希望
希望它存在
对于gcc它确实存在。 gcc libstdc ++具有一组调试容器。对于 std :: vector
,它具有 __ gnu_debug :: vector
调试容器。参见文档。
During active development of a class that uses std::vector
, it often happens that an index is out of bounds. (See this code review question for a practical example.) When using operator[]
, this results in undefined behavior. Still, the []
syntax is easy to read an more convenient than writing .at()
.
Therefore I'd like to write my code using the []
operator, but at the same time have bounds checks enabled. After testing the code, it should be very easy to remove the bounds checks.
I'm thinking of the following code:
util::bound_checked<std::vector<int>> numbers;
numbers.push_back(1);
numbers.push_back(2);
numbers.push_back(3);
numbers.push_back(4);
std::cout << numbers[17] << "\n";
To me, this utility template seems to be so straight-forward that I'd expect it to exist. Does it? If so, under which name?
To me, this utility template seems to be so straight-forward that I'd expect it to exist
For gcc it does exist. gcc libstdc++ has a set of debug containers. For std::vector
it has __gnu_debug::vector
debug container. See documentation.
这篇关于自动检查std :: vector中的边界的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!