std::vector 的编译时触发范围检查

时间:2023-05-09
本文介绍了std::vector 的编译时触发范围检查的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

限时送ChatGPT账号..

目标:

我想要一个范围检查版本的 std::vectoroperator [] 用于我的调试版本,并且在发布模式下没有范围检查.

调试模式下的范围检查显然有利于调试,但它会导致我希望避免的发布代码速度降低 5% - 10%.

可能的解决方案:

我在 Stroustrup 的C++ 编程语言"中找到了解决方案.他做了以下事情:

template 类checked_vector : public std::vector<T>{上市:使用 std::vector::vector;//用at()覆盖操作符[]};

这是有问题的,因为它继承自具有危险的非虚拟析构函数的类.(还有休息室 不太喜欢 喜欢那个解决方案.)

另一个想法是这样的类:

template 类checked_vector {std::vector数据_;上市://手工把所有 std::vector 的公共方法放在这里};

这既乏味又会产生大量的复制粘贴,这也很糟糕.

上述两种解决方案的好处是我可以简单地使用我的 makefile 中的宏定义来打开和关闭它们.

问题:

  1. 有更好的解决方案吗?(如果没有,为什么不呢?)
  2. 如果不是,上述其中一项是否可以接受?(我知道这是基于意见的,如果可能,请关注第一.)

解决方案

如果我没记错的话,这是 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:

  1. Is there a better solution? (If not, why not?)
  2. 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 all three 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 的编译时触发范围检查的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

上一篇:我如何使用 std::vector&lt;std::mutex&gt; 之类的东西? 下一篇:从字符串中获取 IPv4 地址的最快方法

相关文章