Ahmad Siavashi Ahmad Siavashi - 6 months ago 31
C++ Question

Moving raw pointer contents to vector

I have a raw pointer, say,

char * ptr = (char *) malloc(LIMIT);
size_t size;
fill_with_data(ptr, LIMIT, &size);

Now I'd like to wrap the pointer data using

auto v = vector<char>(ptr, ptr + size);

But I think using the syntax above will produce a copy of the pointer's contents. Is there any way to convert a raw pointer to vector without duplicating the data in memory?


A std::vector ¹can't use an existing buffer.

If you want to automate the lifetime management of an existing buffer you can use a smart pointer such as std::unique_ptr or std::shared_ptr.

¹ It's technically possible to use a custom allocator to trick a std::vector into using an existing buffer, but exposing the data in that buffer would have to rely on non-portable aspects of the implementation.