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

后端 未结 3 977
慢半拍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条回答
  •  旧时难觅i
    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 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.

提交回复
热议问题