title: Use of unique_ptr and cudaMalloc
body: <p>I've been thinking about playing around with using std::unique_ptr with device pointers in CUDA. What I was wondering is if the current c++11 unique_ptr can be used in conjunction with cudaMalloc. I know it can be used with normal malloc (<a href="https://stackoverflow.com/questions/3477525/is-it-possible-to-use-a-c-smart-pointers-together-with-cs-malloc">Is it possible to use a C++ smart pointers together with C&#39;s malloc?</a>), but cudaMalloc doesn't return the pointer in the function's return statement. Instead, it returns an error code. The pointer is returned in a reference. </p>
  
  <p>This <a href="https://ernestyalumni.wordpress.com/2017/09/28/bringing-cuda-into-the-year-2011-c11-smart-pointers-with-cuda-cub-nccl-streams-and-cuda-unified-memory-management-with-cub-and-cublas/" rel="noreferrer">blog post</a> recommends the following technique:</p>
  
  <pre><code>auto deleter=[&amp;](float* ptr){ cudaFree(ptr); };
  std::unique_ptr&lt;float[], decltype(deleter)&gt; d_in(new float[size], deleter);
  cudaMalloc((void **) &amp;d_in, size * sizeof(float));
  </code></pre>
  
  <p><strong>Question:</strong> However, I'm concerned that this creates host memory that never gets deleted (i.e. <code>d_in(new float[size], deleter);</code>)?  Unless <code>new float[size]</code> doesn't actually generate host memory or is overridden? If the above doesn't in fact work, could defining my own cudaMalloc wrapper work? - to pass the pointer to unique_ptr?</p>
  
  <p>Something like:</p>
  
  <pre><code>void* myCudaMalloc(size_t mySize){ 
      void * p; 
      checkCUDAerrorMacro(cudaMalloc((void**) &amp;p, size);) 
      return p;
  }
  
  ...
  
  auto deleter=[](float* ptr){ cudaFree(ptr); };
  std::unique_ptr&lt;float[], decltype(deleter)&gt; d_in(myCudaMalloc(size_t mySize), deleter); 
  </code></pre>