首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >类x不存在默认构造函数,运算符新继承。

类x不存在默认构造函数,运算符新继承。
EN

Stack Overflow用户
提问于 2014-06-02 14:33:27
回答 2查看 523关注 0票数 0

我试图实现CUDA博客上给出的统一虚拟内存示例:http://devblogs.nvidia.com/parallelforall/unified-memory-in-cuda-6/

Visual 2013给出了一个错误:类"Term“不存在默认构造函数

代码语言:javascript
复制
#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;
}

类术语不是继承自在管理的父类中定义的新运算符吗?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2014-06-02 14:40:26

这与数据自动化系统无关。编译器没有生成默认构造函数,因为您已经提供了另一个构造函数(复制构造函数)。

只需显式请求默认构造函数:

代码语言:javascript
复制
class Term : public Managed {
public:
    ...

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

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

还请注意,operator new和构造函数是两件不同的事情:new用于分配存储,构造函数用于将该存储初始化为有意义的状态(大致如此)。

票数 1
EN

Stack Overflow用户

发布于 2014-06-02 14:46:13

您需要定义数组元素所需的默认构造函数。

代码语言:javascript
复制
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
};

因为显式定义的复制-ctor Term( const Term&)禁止编译器生成默认构造函数,所以没有。关于=default{}在默认构造函数方面的差异,您可以查看以下内容:

https://stackoverflow.com/a/23698999/1141471

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/23997028

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档