c++cudathrust

Does thrust::device_ptr take over the lifetime of the object it points to?


If I create an object, then wrap it in thrust::device_ptr, does it take over the lifetime of the object? For example:

int* some_memory;
cudaMalloc(some_memory, 100);
thrust::device_ptr thrust_ptr(some_memory);
...
// Should I?
// cudaFree(thrust_ptr.get());
// or thrust::~device_ptr() calls it

Solution

  • As you can see in the thrust::device_ptr documentation:

    Note
    device_ptr is not a smart pointer; it is the programmer’s responsibility to deallocate memory pointed to by device_ptr.

    Therefore it does not take over the lifetime of the object, and so you should take care of freeing the memory once you no longer use it.
    Since memory was allocated with cudaMalloc in your case, cudaFreeing it (as you suggested in the "Should I?" part in your code) is the proper way.