Given a raw array of elements, how to create a std::vector
that takes ownership of the raw array without reallocate & copy?
For example having the raw array:
int* elems = new int[33]
how to create a std::vector
of size 33
pointing to elems
?
I am sure that theoretically this is possible, as usually std::vector
is implemented as a structure containing three pointers, one pointing to the beginning of the allocated memory, one to the end of the valid elements, and one to the end of the allocated memory. But is there a standard way of initializing the std::vector
structure with the raw array?
What you need is a "view" rather than a container. Containers own their elements and their main purpose is to encapsulate the raw memory they manage. If you need to manage the memory yourself then you dont need a container. Take a look at string_view
that would be your solution if you had a string
. Perhaps boost ranges is something that you could apply. From the docs (emphasize mine):
The motivation for the Range concept is that there are many useful Container-like types that do not meet the full requirements of Container, and many algorithms that can be written with this reduced set of requirements. In particular, a Range does not necessarily
- own the elements that can be accessed through it,
- have copy semantics,
PS: Actually std::array_view
was considered for C++17, but unfortunately it didnt make it into the standard.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With