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

后端 未结 3 958
慢半拍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.

提交回复
热议问题