Writing to index of vector beyond end of container

后端 未结 2 588
夕颜
夕颜 2021-01-29 16:14

Why does the following work? I thought that writing to an an index of a vector object beyond the end of the vector object would cause a segmentation fault.

#incl         


        
2条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-29 16:58

    Somebody implementing std::vector might easily decide to give it a minimum size of 10 or 20 elements or so, on the theory that the memory manager likely has a large enough minimum allocation size that it will use (about) the same amount of memory anyway.

    As far as avoiding reading/writing past the end, one possibility is to avoid using indexing whenever possible, and using .at() to do indexing when you truly can't avoid it.

    I find that I can usually avoid doing indexing at all by using range-based for loops and/or standard algorithms for most tasks. For a trivial example, consider something like this:

    int main() {
        vector x(1);
        x.push_back(1);
    
        for (auto i : x)
            cout << i << "\n";
    }
    

    .at() does work, but I rarely find it useful or necessary--I suspect I use it less than once a year on average.

提交回复
热议问题