RemiDav RemiDav - 1 month ago 11
C++ Question

no default constructor exists for class x, operator new inheritence

I was trying to implement the Unified Vidrtual Memory example given on the CUDA blog:
http://devblogs.nvidia.com/parallelforall/unified-memory-in-cuda-6/

Visual Studio 2013 gives me an error : no default constructor exists for class "Term"

#include "cuda_runtime.h"
#include "device_launch_parameters.h"

#include <stdio.h>
#include <iostream>

#define NUM_ATTRIBUTES 10

class Managed {
public:
void *operator new(size_t len) {
void *ptr;
cudaMallocManaged(&ptr, len);
std::cout << "custom new for size " << len << '\n';
return ptr;
}
void *operator new[] (size_t len) {
void *ptr;
cudaMallocManaged(&ptr, len);
std::cout << "custom new for size " << len << '\n';
return ptr;
}
void operator delete(void *ptr) {
cudaFree(ptr);
}
};

class Attribute : public Managed {
public:
int num_levels;
int num_active_levels;
int active_levels;
};

class Term : public Managed {
public:
int num_active_attributes;
int active_attributes;
Attribute attribute[NUM_ATTRIBUTES];

// Unified memory copy constructor allows pass-by-value
Term (const Term &orig) {
num_active_attributes = orig.num_active_attributes;
active_attributes = orig.active_attributes;
cudaMallocManaged((void **)&attribute,NUM_ATTRIBUTES * sizeof(Attribute));
memcpy(attribute, orig.attribute, NUM_ATTRIBUTES * sizeof(Attribute));
}
};

int main()
{
Term * A = new Term[10];
getchar();
return 0;
}


Doesn't the class Term inherit from the new operator defined in the parent class Managed ?

Answer

This is unrelated to CUDA. The compiler isn't generating a default constructor because you have already provided another constructor (the copy one).

Just explicitly request for a default constructor:

class Term : public Managed {
public:
    ...

    // C++11
    Term() = default;

    // Pre C++11 alternative (although not strictly equivalent)
    Term() {}
    ...
};

Also note that operator new and constructors are two different things: new is for allocating storage, constructors are for initializing that storage into a meaningful state (roughly).

Comments