C++ 为避免std:bad\u alloc,图像数据使用什么数据类型?

C++ 为避免std:bad\u alloc,图像数据使用什么数据类型?,c++,image,pointers,void,types,C++,Image,Pointers,Void,Types,我正在开发一个图像库,我正在努力处理图像数据类型 由于图像可以有可变的数据类型(每像素8位,每像素16位),我想实现我的图像数据指针 void* pimage_data; 然而,void*会导致各种各样的肮脏,包括丑陋的指针算法,例如 pimage_data = &((unsigned char*)pimage_parent->m_pdata)[offset_y * pimage_parent->m_pitch + offset_x]; 当我将它传递给另一个方法时,我怀疑

我正在开发一个图像库,我正在努力处理图像数据类型

由于图像可以有可变的数据类型(每像素8位,每像素16位),我想实现我的图像数据指针

void* pimage_data;
然而,void*会导致各种各样的肮脏,包括丑陋的指针算法,例如

pimage_data = &((unsigned char*)pimage_parent->m_pdata)[offset_y * pimage_parent->m_pitch + offset_x];
当我将它传递给另一个方法时,我怀疑它有问题

CImage* roi = CImage::create_image(size_x, size_y, pimage_parent->m_data_type, pimage_data);

CImage* CImage::create_image(int size_x, int size_y, E_DATA_TYPE data_type, void* pimage)
   {
   assert(size_x > 0);
   assert(size_y > 0);

   CImage* image = new CImage(size_x, size_y, data_type);
   image->m_pdata = pimage;

   return image;

   }
新的返回
std::bad_alloc

现在我必须同意,void*并不会直接导致坏的alloc,但我很确定这里有问题。有什么提示吗

编辑:

CImage几乎不起任何作用

CImage::CImage(int size_x, int size_y, E_DATA_TYPE data_type)
   {

   assert(size_x > 0);
   assert(size_y > 0);

   // Copy of the parameter to the class members
   this->m_size_x = size_x;
   this->m_size_y = size_y;
   this->m_data_type = data_type;
   this->m_pitch = size_x;

   // The ctor simply create a standalone image for now
   this->m_pimage_child = NULL;
   this->m_pimage_parent = NULL;

   }

当new抛出bad_alloc时,大小是x:746,y:325,这意味着它无法分配请求的大小。造成这种情况的常见原因是使用了比预期值大得多的垃圾值。但是,对于您的代码,sizeof(CImage)非常大,或者从其他新表达式抛出了bad_alloc


看起来你需要一个构造函数而不是创建一个图像,可能是一个派生类(每个图像类型之一),而不是存储DATAYTYPE。

< P>如果你需要一个带有可变BPP的原始数据的缓冲区,考虑只使用一个数组“<代码>无符号char < /代码>。将访问封装在类中——CImage应该包含它在构造时分配的数组。更好的方法是,使用
std::vector

bad\u alloc可能意味着您的可用内存不足(因为您说sizeof(CImage)==28,您很可能是在一个紧密的或无限的循环中进行操作)。这也可能意味着您已经破坏了freestore,尽管之前的调皮内存行为,它只是在下一个分配/发布周期捕获它。良好的调试会话有助于区分两者。

调用new时,您正在操作的映像的大小是多少?(什么是
size\ux,size\uy
?)我们可以看到CImage的构造函数吗?已被损坏的freestore接受。我在别的地方重写了内存,只是有时候新的内存会把它全部毁掉