问题描述
目标:
我想要一个范围检查版本 std :: vector
'
运算符[]
用于我的调试版本,并且在发布模式下没有范围检查。
调试模式下的范围检查显然适用于调试,但它会导致我的发布代码减慢5% - 10%,我想避免。
strong>可能的解决方案:
我在Stroustrup的C ++编程语言中找到了一个解决方案。他做了以下操作:
模板< class T&
class checked_vector:public std :: vector< T> {
public:
using std :: vector< T> :: vector;
//用at()覆盖operator []
};
这是有问题的,因为它继承一个非虚拟析构函数的类是危险的。 (和 。)
另一个想法是这样的类:
template< class T> ;
class checked_vector {
std :: vector< T>数据_;
public:
//手动将所有公共方法的std :: vector放在这里
};
这样既繁琐,又创建了大量的复制粘贴, p>
上面两个解决方案的好处是我可以简单地在我的makefile中用宏定义来打开和关闭它们。
问题:
- 有更好的解决方案吗? (如果不是,为什么不?)
- 如果不是,上述是否是可接受的? (我知道这是一个基于意见的,如果可能的话,请集中在第一。)
如果我没有误解,这是Visual Studio的通常情况。使用g ++,您必须使用 -D_GLIBCXX_CONCEPT_CHECKS -D_GLIBCXX_DEBUG -D_GLIBCXX_DEBUG_PEDANTIC
调用编译器。 (很可能你不需要所有三个,但我使用所有
三个系统。)与其他编译器,检查文档。这里的标准中未定义的行为的目的正是允许这种事情。
The goal:
I would like to have a range checked version of std::vector
's operator []
for my debug builds and no range check in release mode.
The range check in debug mode is obviously good for debugging, but it causes a slowdown of 5% - 10% in my release code which I would like to avoid.
Possible solutions:
I found a solution in Stroustrup's "The C++ programming language". He did the following:
template <class T>
class checked_vector : public std::vector<T> {
public:
using std::vector<T>::vector;
//override operator [] with at()
};
This is problematic because it inherits from a class with non-virtual destructor which is dangerous. (And the Lounge was not too fond of that solution.)
Another idea would be a class like this:
template <class T>
class checked_vector {
std::vector<T> data_;
public:
//put all public methods of std::vector here by hand
};
This would be both tedious and create a large amount of copy-paste which is bad too.
The nice thing about both the above solutions is that I can simply toggle them on and off with a macro definition in my makefile.
The questions:
- Is there a better solution? (If not, why not?)
- If not, is one of the above considered acceptable? (I know this one is opinion based, please focus on No. 1 if possible.)
If I'm not mistaken, this is the usual situation with Visual Studio. With g++, you have to invoke the compiler with -D_GLIBCXX_CONCEPT_CHECKS -D_GLIBCXX_DEBUG -D_GLIBCXX_DEBUG_PEDANTIC
. (It's probable that you don't need all three, but I use allthree systematically.) With other compilers, check the documentation. The purpose of the undefined behavior in the standard here is precisely to allow this sort of thing.
这篇关于编译std :: vector的时间触发范围检查的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!