在 C++ 中将 malloc/free 替换为 new/delete



我只是想确定一下。

这是我的代码

int * Image = (int *)malloc(sizeof(int) * m_Width/2 * m_Height);
free(Image);

如果我想使用新的而不是 malloc 和免费而不是删除。这是我写的

int* Image = new int[m_Width/2 * m_Height];
delete[] Image;

这是对的吗?

从技术上讲,这是正确的。 但是,这就是我们正在谈论C++,动态分配数组的C++方法是改用std:vector

std::vector<int> Image(m_Width/2 * m_Height);

或:

std::vector<int> Image;
Image.resize(m_Width/2 * m_Height);

std::vector超出范围时,内存将被销毁时自动释放。

错。但是,如果您想在不获得太多 OOP 开销的情况下获得一些额外的语义,您可以使用unique_ptr:

unique_ptr<int[]> Image(new int[m_Width/2 * m_Height]);
// do something with Image...
Image.Reset(); // call it if you want to free memory manually,
               // or just leave until Image is destroyed. 

最新更新