C++ Logo

std-proposals

Advanced search

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

From: Giuseppe D'Angelo <giuseppe.dangelo_at_[hidden]>
Date: Fri, 22 Dec 2023 18:00:48 +0100
Hello,

Il 22/12/23 17:15, ஜெய்கணேஷ் குமரன் via Std-Proposals ha scritto:
> At the moment there appeärs to be no way to create a std::vector or
> std::string from an existing memory buffer, or take ownership of the
> memory owned by std::vector or std::string.
> This is very limiting in interoperability scenarios where you may not be
> able to expose a std::vector or std::string directly.
>
> Technically, a custom allocator could be used that provides existing
> memory but still the actual objects cannot are not considered.
>
> I propose having .attach and .detach member functions on std::vector and
> std::string.
> They should take in or return the following respectively, in a structure
> perhaps: pointer to the data (.data), count of the elements
> (.size/length), capacity of the buffer (.capacity) and the allocator
> instance.

I'm not saying that this doesn't make any sense, but if you want to
stand any chance of actually proposing this, you'd need to survey *a
lot* of stdlib implementations and determine that vector/string is
always implemented in a way that allows such attaching/detaching.


For strings, SSO poses already a challenge (e.g. there may be no extra
allocated memory to detach, what happens?).


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.


My 2 c,
-- 
Giuseppe D'Angelo

Received on 2023-12-22 17:00:52