C++ Logo


Advanced search

Re: [std-proposals] Attaching and detaching memory from std::vector or std::string

From: ஜெய்கணேஷ் குமரன் <jaiganesh.kumaran_at_[hidden]>
Date: Thu, 28 Dec 2023 06:02:24 +0000
For strings, SSO poses already a challenge (e.g. there may be no extra allocated memory to detach, what happens?).

In this case ideally let the user handle it manually. Though for simplicity, you could choose to let std::string make a copy and then hand it over (also SSO need not necessarily be implemented).

In general, it is perfectly legitimate for a vector/string implementation to be like this:

template <class T> class vector {
 vector_data<T> *data;

where `data` is nullptr in case of 0 capacity, otherwise points to a "dynamically sized" data structure like:

struct vector_data {
 size_t size;
 size_t capacity;
 T actual_data[1]; // not really 1, but #capacity elements

In this case you can't just attach/detach a contiguous array of T*; there's no such thing.

Do these implementations exist? Will they ever see C++26?
Hence the need of surveying them.

I have checked the three major implementations (MSVC STL: https://github.com/microsoft/STL/blob/main/stl/inc/vector#L423, libc++: https://github.com/llvm/llvm-project/blob/main/libcxx/include/vector#L726 and https://github.com/gcc-mirror/gcc/blob/master/libstdc%2B%2B-v3/include/bits/stl_vector.h#L93) and none of them use a 'flexible array' with the size and capacity stored inside the allocated memory.

If there is another implementation that does this however, they would need to change it, which may not be possible due to ABI. But I also don't think it's too bad make .attach and or .detach copy the data as a fallback.

Received on 2023-12-28 06:02:30