删除动态分配的内存的最佳做法是什么?

What is best practice to delete dynamically allocated memory?

我不得不用 new 关键字多次重新分配 iScreenoScreen

我发现在重新分配新的堆内存之前我必须每次都delete它们。

这对我来说似乎是不好的做法。有没有更好的办法解决这个代码重复问题?

Matrix* oScreen;
Matrix* iScreen;

iScreen = new Matrix(100, 100);
oScreen = new Matrix(100, 100);

//do something with iScreen, oScreen

delete iScreen; // have to write same "delete iScreen" every single time?
iScreen = new Matrix(150, 150);
delete oScreen;
oScreen = new Matrix(150, 150);

考虑将动态对象保存在容器中,例如 std::vector if you can. Otherwise, they should be managed by a smart pointer like std::unique_ptr

std::unique_ptr<Matrix> iScreen;

iScreen = std::make_unique<Matrix>(100, 100);

// do something with iScreen

iScreen = std::make_unique<Matrix>(150, 150); // no need to delete

您不必删除旧的,智能指针会在您分配新指针时自动删除。