| 179 | |
| 180 | template <typename T> |
| 181 | class cuda_data_ptr |
| 182 | { |
| 183 | /*! |
| 184 | WHAT THIS OBJECT REPRESENTS |
| 185 | This is a block of memory on a CUDA device. It is just a type safe |
| 186 | version of cuda_data_void_ptr. |
| 187 | !*/ |
| 188 | |
| 189 | public: |
| 190 | |
| 191 | static_assert(std::is_standard_layout<T>::value, "You can only create basic standard layout types on the GPU"); |
| 192 | |
| 193 | cuda_data_ptr() = default; |
| 194 | cuda_data_ptr(size_t n) : num(n) |
| 195 | /*! |
| 196 | ensures |
| 197 | - This object will allocate a device memory buffer of n T objects. |
| 198 | - #size() == n |
| 199 | !*/ |
| 200 | { |
| 201 | if (n == 0) |
| 202 | return; |
| 203 | |
| 204 | pdata = cuda_data_void_ptr(n*sizeof(T)); |
| 205 | } |
| 206 | |
| 207 | cuda_data_ptr( |
| 208 | const cuda_data_ptr<typename std::remove_const<T>::type> &other |
| 209 | ) : num(other.num), pdata(other.pdata) {} |
| 210 | /*! |
| 211 | ensures |
| 212 | - *this is a copy of other. This version of the copy constructor allows |
| 213 | assigning non-const pointers to const ones. For instance, converting from |
| 214 | cuda_data_ptr<float> to cuda_data_ptr<const float>. |
| 215 | !*/ |
| 216 | |
| 217 | T* data() { return (T*)pdata.data(); } |
| 218 | const T* data() const { return (T*)pdata.data(); } |
| 219 | |
| 220 | operator T*() { return (T*)pdata.data(); } |
| 221 | operator const T*() const { return (T*)pdata.data(); } |
| 222 | |
| 223 | void reset() { pdata.reset(); } |
| 224 | |
| 225 | size_t size() const { return num; } |
| 226 | /*! |
| 227 | ensures |
| 228 | - returns the number of T instances pointed to by *this. |
| 229 | !*/ |
| 230 | |
| 231 | operator cuda_data_void_ptr() const |
| 232 | /*! |
| 233 | ensures |
| 234 | - returns *this as a cuda_data_void_ptr. Importantly, the returned size() will |
| 235 | reflect the number of bytes referenced by *this. To be clear, let P be the |
| 236 | returned pointer. Then: |
| 237 | - P.get() == get() |
| 238 | - P.size() == size() * sizeof(T) |