我有一个类,其中包含一个指向 RGB 值数组的浮点类型缓冲区。缓冲区已正确创建和存储,但是当我通过函数将此类的实例返回到 main() 时,缓冲区的内存不可读。这是初始类:
namespace imaging
{
typedef float component_t;
class Image
{
protected:
component_t * buffer;
unsigned int width, height;
public:
Image(unsigned int width, unsigned int height, const component_t * data_ptr) {
this->width = width;
this->height = height;
this->setData(data_ptr);
this->buffer = const_cast<component_t *>(data_ptr);
}
component_t getRedValPixel(unsigned int x, unsigned int y) const {
int pos = x * this->width * 3;
component_t red;
red = this->buffer[pos];
return r;
}
}
}
为了创建此类的实例,我使用 readImage(char* filepath) 方法,该方法在加载数据后具有以下 return 语句:
return &Image(width, height, buffer);
这是main()函数中的代码:
Image* image = readIamge(filepath);
int width = image->getWidth(); //retrieves it correctly
int height = image->getHeight(); //retrieves it correctly
for (int i = 0; i < height; i++) {
for (int j = 0; j < width; j++) {
cout << image->getRedValPixel(i,j);
}
}
最佳答案
让我们仔细看看您的返回声明:
return &Image(width, height, buffer);
当您执行Image(...)
时,会创建一个临时对象。一旦它所在的表达式结束,这个临时对象就会被销毁。然后,您返回一个指向该临时对象的指针,该对象随后将立即消失,并留下一个指向不存在对象的指针。尝试取消引用该指针将导致未定义的行为。
您从文件中读取的数据可能仍在内存中的某个位置,但无法从您返回的指针中获取。
我建议您按值返回对象并研究移动语义、移动构造函数和the rules of three, five and zero 。我还建议您不仅复制指向对象实际数据的指针,还复制实际数据本身(深层复制)。
关于c++ - float 类型 创建对象 C++ 后丢失的缓冲区内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40402329/