在动态分配中,在关键字new之前使用Why(unsigned char*)

Why (unsigned char *) is used before the key term new in dynamic allocation

本文关键字:Why unsigned char 动态分配 关键字 new      更新时间:2023-10-16

我在一些2D charImage的动态内存分配教程中遇到了charImage = (unsigned char *) new unsigned char [M*N]。M和N是图像的行数和列数。

charImage在程序开始时被声明为无符号的char指针。

'new'之前的(unsigned char*)是什么意思?

有人能解释一下吗?

它是一个可用于将一种类型转换为另一种类型的强制转换运算符。在这种特殊情况下,它不是必需的,因为原始变量已经是一个无符号字符。由于类型已经匹配,所以强制转换不会执行任何操作。

这意味着您正在分配M*N个无符号字节的内存,而您的charImage变量是指向此类数组的指针*(指向无符号字符的指针,因此是unsigned char *

如果你仔细查看.h文件,你会发现charImage变量定义为:

unsigned char *charImage;

这不是必需的。代码将返回的指针强制转换为指针类型,因此基本上是no-op。如果你删除它,不会有什么不好的事情发生!

它是unsigned pointer to char的强制转换。

它不仅是不需要的(在您的示例中,char[]会隐式转换为char*),而且是C++中不推荐使用的C样式的强制转换。

如果您确实需要在C++中执行强制转换,那么您应该使用以下选项之一:

dynamic_cast<type>
static_cast<type>
reinterpret_cast<type>
const_cast<type>

每个人都扮演着不同的角色。

你可以在这里找到许多关于这个主题的教程之一:http://www.cplusplus.com/doc/tutorial/typecasting/

从C++11开始,您可以使用术语"auto"来减轻重新键入对象类型(出错)的一些负担

constexpr auto COLUMNS  = 640;
constexpr auto ROWS     = 480;
unsigned char  img[COLUMNS*ROWS];
// auto ptr_to_img = img; // or = &img[0]; //or see line below
auto ptr_to_img = new unsigned char[COLUMNS*ROWS];

在大多数情况下,您也可以使用Boost(1.56)类型索引库来告诉您对象的类型

#include <boost/type_index.hpp>
using std::cout;
using boost::typeindex::type_id_with_cvr;
//...
cout    << "COL type   : "
        << type_id_with_cvr<decltype(COLUMNS)>().pretty_name() << 'n';
cout    << "ROWS type  : "
        << type_id_with_cvr<decltype(ROWS)>().pretty_name() << 'n';
cout    << "Image type : "
        << type_id_with_cvr<decltype(img)>().pretty_name() << 'n';
cout    << "Ptr to Image type : "
        << type_id_with_cvr<decltype(ptr_to_img)>().pretty_name() << 'n';

结果是以下

COL type   : int const
ROWS type  : int const
Image type : unsigned char [307200]
Ptr to Image type : unsigned char*

最后一句话是,在C++中不鼓励使用原始指针,因为某个地方必须存在专门用于存储图像的正确容器。

该对象将更容易由智能指针管理(当你去掉图像时,智能指针将负责自动恢复内存)。

即使必须连接到纯C库(只能在C库的接口处转换为传统形式),这也可能有效但我不知道C++图像库是如何解决这个问题的,这可能是这个网站的一个问题。之前看一下一些C++映像库。Boost也有一个(GIL)。

相关文章: