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];
}