Search code examples
c++dynamic-memory-allocationnew-operatorheap-memorydelete-operator

What is best practice to delete dynamically allocated memory?


I have to reassign iScreen and oScreen many times with new keyword.

I found that I have to delete them every single time before reassign new heap memory.

It seems like bad practice to me. Is there any better way to solve this code repetition?

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);

Solution

  • Consider holding your dynamic objects in a container like 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
    

    You don't have to delete the old one, the smart pointer does that automaticaly when you assign a new one.