1

A memory block holds values I'd like to use as an std::vector. I currently copy the values over using std::memcpy.

#include <cstdlib>
#include <cstring>
#include <vector>
int main()
{
    const std::size_t count = 2097152;
    float* ptr = (float*)std::malloc(count * sizeof(float)); // raw ptr for simplicity
    // ...
    std::vector<float> vec(count, 0);
    std::memcpy(vec.data(), ptr, count * sizeof(float));
    //...
    std::free(ptr);
}

However the copying is unnecessary, since ptr is no longer needed at this point. How can I make std::vector reuse the memory and take normal ownership of it?

Tobias Hermann
  • 9,936
  • 6
  • 61
  • 134
  • 2
    [Read up on allocators](http://en.cppreference.com/w/cpp/concept/Allocator) – user4581301 Feb 05 '18 at 20:41
  • FWIW: If you need to pass a pointer to a legacy function to have the data populated you can just use `std::vector info(some_size); legacy_function(info.data());` and now the vector has the information in it. – NathanOliver Feb 05 '18 at 20:44

0 Answers0