RAII模式管理CUDA资源?unique_ptr with custom deleter?RAII模式管理CUDA资源?unique_ptr with custom deleter?
RAII(Resource Acquisition Is Initialization):构造时获取资源、析构时释放,避免泄漏与重复释放。CUDA 资源如 device 指针、stream、event、context 等都应「谁创建谁释放」,用 RAII 封装可防止异常路径泄漏。
std::unique_ptr<T, Deleter> 在析构时调用 Deleter。对 device 指针:Deleter 里调用 cudaFree(ptr.get());对 stream:cudaStreamDestroy;对 event:cudaEventDestroy。定义 using CudaPtr = std::unique_ptr<float, decltype(&cudaFree)> 或写一个 functor 封装 cudaFree,即可 CudaPtr p(ptr, cudaFree),出作用域自动释放。
可封装成 CudaDevicePtr<T>、CudaStream、CudaEvent 等类,拷贝禁用、移动允许;与 STL 容器配合时注意 deleter 类型一致。避免 raw new/delete 与 cudaMalloc/cudaFree 混用导致的双重释放。
| 返回模块 | 返回总览 |