c++ - float 类型 创建对象 C++ 后丢失的缓冲区内容

标签 c++ buffer typedef

我有一个类,其中包含一个指向 RGB 值数组的浮点类型缓冲区。缓冲区已正确创建和存储,但是当我通过函数将此类的实例返回到 ma​​in() 时,缓冲区的内存不可读。这是初始类:

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);

这是ma​​in()函数中的代码:

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/

相关文章:

具有可变数字或参数的函数的 C++ 静态编译

c++ - 将enum类变量reinterpret_cast转换为基础类型的引用是否安全?

c++ - 关于 std::basic_ostream::write

node.js - 为什么 isBuffer 对于不编码的 fs.readFileSync 调用返回 false

C 语言,段错误(已创建核心转储)

c++ - 按值返回的对象分配的位置

c++ - 错误 : Expected a ')' ?

C编程: write to file without buffer

c - C中结构成员值的自赋值

c++ - 为什么模板 typedef 是 C++(不是 C++11)中的一个问题