将 malloc 转换为新的正确方法

The correct way to convert malloc to new

本文关键字:方法 malloc 转换      更新时间:2023-10-16

我正在将 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_ptrstd::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