Is accessing the raw pointer after std::vector::reserve safe?

后端 未结 3 980
慢半拍i
慢半拍i 2020-12-11 17:07

This is pretty farfetched, but is the following code \"safe\" (i.e. guaranteed not to cause segmentation fault):

std::vector vec(1); // Ensures th         


        
3条回答
  •  被撕碎了的回忆
    2020-12-11 17:53

    No, it is not safe.

    After a reserve(), the vector is guaranteed not to reallocate the storage until the capacity() is reached.

    However, the standard doesn't say what the vector implementation can do with the storage between size() and capacity(). Perhaps it can be used for some internal data - who knows? Perhaps the address space is just reserved and not mapped to actual RAM?

    Accessing elements outside of [0..size) is undefined behavior. There could be some hardware check for that.

提交回复
热议问题