将 malloc 转换为新的正确方法
The correct way to convert malloc to new
我正在将 c 代码更改为 c++ 代码,这就是我将 malloc 转换为新的
frame.p_data = (uint8_t*)malloc(xres * yres * 4);
free(frame.p_data);
frame.p_data = (uint8_t*)operator new(xres * yres * 4);
delete(frame.p_data);
这是从malloc更改为新的正确方法吗,删除会释放所有数据吗?
不,你应该写
frame.pdata = new uint8_t[xres * yres * 4];
delete [] frame.pdata;
显式调用分配函数是非常罕见的,operator new
,但如果这样做,则需要将其与释放函数匹配,operator delete
,否则行为是未定义的:
frame.p_data = (uint8_t*)operator new(xres * yres * 4);
operator delete(frame.p_data);
将malloc
与基元类型一起使用也不是问题,只要您记得使用free
进行释放,但更容易坚持new
/delete
而不必记住。
这个答案显示了如何使用new/delete,但这个建议似乎不正确/不完整。
正确的方法(将通过主流代码审查(不是首先用new
/delete
替换它,而是直接转到容器/智能指针。std::vector
(如果静态大小,则std::array
(具有所需的所有工具,因为std::vector
是 C++ 中的动态数组。如果尺寸跟踪开销太大,则std::unique_ptr
或std::array
。
简化示例:
std::vector<uint8_t> data;
data.resize(xres * yres * 4);
uint8_t* pdata = data.data(); // <- access to raw buffer
关于这方面的一些准则:
https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#Rr-newdelete
https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#Ri-raw
相关文章:
- 为不同配置设置MSVC_RUNTIME_LIBRARY的正确方法是什么
- 通过方法访问结构
- 最小硬币更换问题(自上而下方法)
- C++为构建时间获取QDateTime的可靠方法
- 如果没有malloc,链表实现将失败
- 在C#中处理C++指针而不使用unsafe的最佳方法
- 处理多个异常集合的C++方法
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗
- 有什么方法可以遍历结构吗
- 当类在C++中定义时,有什么方法可以"register"类吗?
- 在C++中,将大的无符号浮点数四舍五入为整数的最佳方法是什么
- 实现无开销push_back的最佳方法是什么
- 使用std::函数映射对象方法
- 有符号的int和int-有没有一种方法可以在C++中区分它们
- C++从另一个类访问公共静态向量的正确方法是什么
- 将 malloc 转换为新的正确方法
- 在混合 C/C++ 程序中协调 malloc 和 new 的"正确"方法是什么?
- 在方法上使用malloc,在主要工作中自由
- 执行主机端 malloc 和异步主机到设备 memcpy 的规范方法
- c++中的malloc/free:为什么free不接受const void*,有没有更好的方法?