0

I want to create an array of type cuda_ptr without calling the default constructor.

My cuda_ptr class looks like the following:

template <typename T>
class cuda_ptr
{
    public:

    cuda_ptr(){}
    cuda_ptr(size_t device_number, T* allocdata ){
        
        std::cout<<"create pointer"<<std::endl;
        dev_number = device_number;
        safeCudaSelectDevice(dev_number);
        data = allocdata;
    }
    ~cuda_ptr(){
        safeCudaSelectDevice(dev_number); cudaFree(data);
        std::cout<<"delete pointer"<<std::endl;
    }
    
    size_t dev_number = 0;
    T* data;

    
};

Now Im creating a single object this way, (safeCudaMalloc's return type is T*)

cuda_ptr<float> a(0, safeCudaMalloc<float>(N* sizeof(float)));

This all works as intended. Now I want to create an array of fixed size. My Idea was to use the following:

cuda_ptr<T> dev_A[2];

And then fill it using the self written constructor:

  for(int i = 0; i<2;i++){
      dev_A[i] = cuda_ptr<T>(i, safeCudaMalloc<T>(N* sizeof(T)));
   }

However, this gives me some problems. First of all, my class should not even have a default constructor, as this gives me more problems. Secondly, if I try out this code, create pointer and delete pointer show up on the console right after each other. Does that mean my pointer gets deleted right after it got created? And my overall question is, is there a better way to initialize and fill my array such that I dont have to call the default constructor? Thanks in advance!

JanJHF
  • 7
  • 3
  • [Rule of 3/5/0](https://en.cppreference.com/w/cpp/language/rule_of_three). – Eljay Jun 28 '22 at 11:07
  • Defining an array as `cuda_ptr dev_A[2];` default-initialises elements of the array - and for a class type, that calls the default constructor. Change this (C++11 or later) to `cuda_ptr dev_A[2] = { {0, safeCudaMalloc(N* sizeof(T))}, {1, safeCudaMalloc(N* sizeof(T))} };` or (before C++11) to `cuda_ptr dev_A[2] = { cuda_ptr(0, safeCudaMalloc(N* sizeof(T))), cuda_ptr(1, safeCudaMalloc(N* sizeof(T))) };`. Either way, remove the loop. It would probably be better to avoid all this by using a standard container (possibly with a tailored allocator). – Peter Jun 28 '22 at 11:08

0 Answers0