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

后端 未结 3 956
慢半拍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:43

    Vector-reallocation invalidates existing pointers, references etc. Reserve could trigger a reallocation (23.3.6.2, [vector.capacity]) but you are taking the address of the first element after the eventual reallocation (which in this case will not probably happen at all, but that's besides the point). So I see no problem with the code.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-11 18:02

    First note that your memset will truncate the 0x123 to a single byte and write that, not writing a four byte pattern.

    Then, don't do that, just use the container: std::vector<int> vec(100, whatever_value_you_want);

    However to answer the question it may appear to work specifically for POD types if the compiler doesn't use the allocated space for anything. Certainly if anyone calls resize, insert, push_back etc it'll blow away whatever you've already written into the memory and the size of the vector will be wrong as well. There's just no reason to write such code.

    0 讨论(0)
提交回复
热议问题