Compile time triggered range check for std::vector

后端 未结 2 1696
自闭症患者
自闭症患者 2020-11-29 06:57

The goal:

I would like to have a range checked version of std::vector\'s operator [] for my debug builds and no range chec

2条回答
  •  暖寄归人
    2020-11-29 07:29

    In decreasing order of preference:

    • If you utilize iterators, ranges, and iteration rather than indexes into the container, the problem just goes away because you are no longer passing in arbitrary indexes that need to be checked. At that point you may decide to replace any remaining code that requires indexes with at instead of using a special container.

    • Extend with algorithms rather than inheritance as suggested in one of the comments. This will almost certainly be completely inlined away and is consistent with the standard using algorithms rather than additional member functions. It also has the advantage of working with any container that has operator[] and at (so it would also work on deque):

      template 
      const typename Container::value_type& element_at(const Container& c, int index)
      {
          // Do checked code here.
      }
      
    • Privately inherit std::vector and using the methods you need into your child class. Then at least you can't improperly polomorphically destroy your child vector.

提交回复
热议问题