在动态分配中,在关键字new之前使用Why(unsigned char*)
Why (unsigned char *) is used before the key term new in dynamic allocation
我在一些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)。
- 从"int*"强制转换为"unsigned int"会丢失精度错误
- 不能在初始值设定项列表中将非常量表达式从类型 'int' 缩小到'unsigned long long'
- Why is UINT32_MAX + 1 = 0?
- <Windows>为什么 std::thread::native_handle 返回类型为"long long unsigned int"的值,而不是 void*(又名 HANDLE)?
- 错误:隐式转换更改符号:'int'到'unsigned long'
- 如何使用多次 memcpy 转换回 std::vector<unsigned char>?
- 定义 uint= "unsigned int" 没有像我在 Visual Studio 中使用 nvcc 时预期的那样应用
- static_cast<unsigned>(签名)与标准::bit_cast<unsigned>(签名)之间有区别吗?
- 对 '(const Y) (int&, std::mersenne_twister_engine<long unsigned int,
- 错误:从'void*'到'const uint8_t* {aka const unsigned char*}'的转换无效 [-允许]
- 错误:'class std::unique_ptr<std::set<long unsigned int> >'没有名为 'size' 的成员
- 为什么在C++负数static_cast如果<unsigned>数字是常数,则不同
- 正确语法,用于统一初始化名称中带有空格的类型的临时,如unsigned int
- Why (int)pow(2, 32) == -2147483648
- "1L << count"是什么意思?如何使用超出"unsigned long long int? "范围的语句编号打印?
- C++ - 从 "int" 到 "unsigned char" 的缩小转换无效
- 让 'std::vector<unsigned char>' 从 'std::string' 中窃取内存
- C++11 模板函数"implicity"将位集<N>转换为"unsigned long"
- "runtime error: addition of unsigned offset to 0x129000a0 overflowed to 0x12900088"
- 在动态分配中,在关键字new之前使用Why(unsigned char*)