Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I cudaMemcpy from device straight into host STL vector?

Pretty much as the title says - I plan to .reserve() some memory on the host via an STL vector, and then cudaMemcpy an array from device to host (i.e. into that reserved host memory).

Will the STL vector pick up on the fact I have (by external methods) copied new data into the vector? I.e. will it correctly

  • Identify the new size it should be?
  • Allow me to access the data via [i]-indexing or iterators?
  • Behave as expected in general, i.e. like any normal vector?
like image 996
mchen Avatar asked Jan 26 '26 21:01

mchen


1 Answers

Will the STL vector pick up on the fact I have (by external methods) copied new data into the vector? I.e. will it correctly.

No, it won't, since you just reserved, without actually resizing the vector. reserve is just a request to reserve internal storage, for the sake of reducing memory allocation overhead and preventing iterator invalidation. It doesn't change the container's size as viewed from the outside.

What would work though would be to call resize instead of reserve. In this case you can then freely copy data directly into the vector, since its storage is guaranteed to be contigous and of appropriate size. In this case all of your points will hold. But note that resize comes with the possible overhead of default constructing the data for the to be writen to elements, but preventing this overhead is a different question, resizeing the vector is still the only possible way to achieve what you're after.

like image 76
Christian Rau Avatar answered Jan 28 '26 20:01

Christian Rau



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!