C++ 我可以从前面提到的实例变量中获取初始化列表中数组的堆内存吗?

C++ 我可以从前面提到的实例变量中获取初始化列表中数组的堆内存吗?,c++,new-operator,rvalue,lvalue,initialization-list,C++,New Operator,Rvalue,Lvalue,Initialization List,我试图在自定义构造函数中创建对象时为数组在堆上分配内存。数组的大小由先前初始化的实例变量决定。为了清楚起见,这里是我的代码 struct PNG { PNG() = delete; PNG(unsigned width, unsigned height): d_width(width), d_height(height), d_imageData(new unsigned int [d_width * d_height])

我试图在自定义构造函数中创建对象时为数组在堆上分配内存。数组的大小由先前初始化的实例变量决定。为了清楚起见,这里是我的代码

struct PNG {

    PNG() = delete;
    PNG(unsigned width, unsigned height):
        d_width(width),
        d_height(height),
        d_imageData(new unsigned int [d_width * d_height])
    {
    };

    PNG(PNG const &);

    PNG & operator = (PNG & other);

    friend std::ostream & operator << (std::ostream & os, PNG & png);

    unsigned d_width;
    unsigned d_height;
    unsigned d_imageData; // unsigned d_imageData []; has the same issue
};
我被两件事弄糊涂了:

  • 在我看来,数组将请求内存,因此 是一个容器,因此是一个
    左值
    ,而不是一个不会 有储藏室
  • 变量
    d_width
    d_height
    在初始化列表中提及后是否可以访问
  • 我看到它是这样做的,但我想尝试初始化列表。现在,我正在通过玩代码学习一些新的东西。这是唯一可行的方法吗

    PNG(unsigned int width, unsigned int height) {
        width_ = width;
        height_ = height;
        imageData_ = new HSLAPixel[width * height];
      }
    

    很接近,但它使用了
    std::initializer\u list
    ,我不打算使用,也不需要接受答案中建议的模板。更重要的是,数组值将在以后填充,而不是在对象构造时填充

    您的构造函数很好。但是,由于您正在使用
    new[]
    d\u imageData
    分配内存,因此需要将
    d\u imageData
    声明为指针类型,而不是整数类型,例如:


    unsigned int*d_imageData;//您可能还希望提及一些选项,例如使用
    std::vector
    或其他一些标准容器,因为它们可以简化动态分配的ArrayShank的管理。我真傻。为什么编译器会提到
    rvalue
    ?它是指类型,
    unsigned int
    还是
    [d_width*d_height]
    ?@heretoinfinity-提到的右值是新的
    表达式的结果。编译器可能以一种过于复杂但技术上正确的方式告诉您,
    新的
    表达式(指针
    无符号int*
    )的结果不能存储在
    无符号int
    @Peter中,谢谢。我应该提到,现有的实现使用数组。我只是在玩代码,试图理解如何自己组合
    operator=
    ,以确保我理解它,并从这个“摆弄”开始理解初始化列表。如果我自己从头开始设计的话,我会选择
    std::vector
    PNG(unsigned int width, unsigned int height) {
        width_ = width;
        height_ = height;
        imageData_ = new HSLAPixel[width * height];
      }