Using operator[] on empty std::vector

前端 未结 7 924
迷失自我
迷失自我 2021-01-12 05:29

I was advised a while ago that is was common place to use std::vector as exception safe dynamic array in c++ rather than allocating raw arrays... for exampl

7条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-12 06:26

    If you want to get cleaner behaviour in this scenario you could replace use of a[0] with use a.at(0), which will throw if the index is invalid.

    A pragmatic solution would be to init vector with n+1 entries and constrain access to 0..n-1 (as this code already does).

    void foo (int n) {
       std::vector scoped_array (n+1);
       char* pointer = &scoped_array[0];
       file.read ( pointer , n );
       for (int i = 0; i < n; ++i) {
      //do something
       }
    }
    

提交回复
热议问题