类x没有默认构造函数,operator new继承
no default constructor exists for class x, operator new inheritence
我试图实现CUDA博客上给出的统一虚拟内存示例:http://devblogs.nvidia.com/parallelforall/unified-memory-in-cuda-6/
Visual Studio 2013给了我一个错误:没有默认构造函数存在类"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;
}
类Term不是继承自父类Managed中定义的新操作符吗?
这与CUDA无关。编译器没有生成默认构造函数,因为您已经提供了另一个构造函数(复制构造函数)。
只是显式请求默认构造函数:
class Term : public Managed {
public:
...
// C++11
Term() = default;
// Pre C++11 alternative (although not strictly equivalent)
Term() {}
...
};
还要注意,operator new
和构造函数是两个不同的东西:new
用于分配存储,构造函数用于将存储初始化为有意义的状态(大致)。
您需要定义一个默认构造函数,该构造函数是数组元素所必需的
class Term : public Managed {
public:
//...
Term () {} // default c-tor
Term() = default; // since C++11, note however that there are some
// differences between Term() = default; and Term() {}
// they are not equal when value initialization
// is considered
};
没有,因为显式定义的copy-ctor Term( const Term&)
禁止编译器生成默认构造函数。关于=default
和{}
在默认构造函数方面的差异,您可以查看以下内容:
相关文章:
- 过载'operator new'如何导致无限循环?
- 在C++中调用 malloc() 与"operator new"函数之间的实现差异
- C++和组装:通过ASM呼叫'operator new'和'operator delete'
- 'operator new':函数不接受 2 个参数
- 错误 C2661:'CObject::operator new':没有重载函数需要 4 个参数
- 错误 35 错误 C2661:'operator new':没有重载函数占用 2 个参数
- 什么是"::operator new"和"::operator delete"?
- void* in malloc vs operator new
- 我们还需要"placement new"和"operator new"吗?
- 'operator new'的第一个形式参数必须'size_t'
- 正在对使用operator new okay的放置delete操作的结果调用delete
- operator new[]在MSVC调试时非常慢
- ::operator new[]()与::operator new()有什么不同?
- 为什么替换malloc()需要了解链接器,而::operator new()不需要
- 带nothrow选项的Operator new仍然会抛出异常
- :operator delete(void*)是否知道使用::operator new(size_t)分配的内存大小
- 类x没有默认构造函数,operator new继承
- 如何使用operator new对包含复合类的派生类进行直接初始化
- 如何使用operator new创建动态2D字符数组
- 执行operator new的任何实现都返回指向大小为零的数组的保护页的指针