TL; DR:
How do I resize (adjust both length
and capacity
of) a C++ STL vector without any initialization? Garbage values are acceptable!
Question
I am aware that STL Vector has resize()
method, but this method involves initialization, which might be unnecessary.
Moreover, I found a set_len()
function in Rust which does what I want exactly. Is there a way (even hacky) for C++ STL to achieve this?
The set_len()
doc in Rust can be found here.
EDIT 1
I am aware that setting a length that is larger than the vector's capacity is undefined behavior, and I have to be very careful (
unsafe fn
, sure enough), but I am talking about those cases wherethe_new_length_i_am_setting <= vec.capacity()
is GUARANTEED (I have alreadyreserved()
correctly).I don't really care what values will be filled into those extra spaces (garbage is acceptable) since I will manually overwrite them carefully afterward. The difference between
malloc()
andcalloc()
is a perfect analogy of what I am talking about.My use case: store bytes from multiple
read()
s orrecv()
s calls into the same vector directly without using an extra array/buffer. (I have achieved this in Rust's Vec usingreserve()
and thenset_len()
, but I failed to find an equivalent function forset_len()
in C++ STL'svector
.To make things easier to understand, I am basically trying to use
vector
on Linux system APIs which only arrays are accepted. Callingrealloc()
on amalloc()
-ed array will definitely do the same, but it is error-prone, especially when dealing with indices.