0

If I'm using an assignment operator overload with dynamic memory should I check to see if there's something inside the pointer already?

for example if object A has a dynamic memory allocation in the constructor for an array called "name".

stored in object A is the name "John" with the memory allocated in the constructor through

name = new char[strlen(userinput)+1];

If I wanted to copy object B into object A through an assignment operator overload would I have to write

if(name != null){delete [] name;}
name = new char[strlen(src.name)+1];

To first clear the array out or do I not have to delete name before reallocating memory?

user3551329
  • 3
  • 1
  • 1
  • 6
  • One `delete[]` per `new[]`, and no need for a null check. – chris Apr 18 '15 at 23:49
  • 2
    If you are juggling with dynamically allocated memory, there's probably more to fix than what you're asking for. I'd seriously recommend using a `std::vector` instead of struggling `new/delete` yourself. – πάντα ῥεῖ Apr 18 '15 at 23:51
  • @user3551329 you don't actually have to test `if(name != nullptr)`, since deleting a `nullptr` is a no-op. Just `delete[] name;` should do. – vsoftco Apr 19 '15 at 00:21

1 Answers1

2

"To first clear the array out or do I not have to delete name before reallocating memory?"

This way, you have to take care about memory management and de-/allocation all the time. You have to obey for copy constructions, assignments also (see What is the Rule of Three?).

if(name != nullptr){delete [] name;}
        // ^^^^^^^ The correct term is nullptr

You have to manage the nullptr value yourself. delete/delete [] don't assign a nullptr value automatically, but leave you with a dangling pointer.


The better solution instead of managing dynamically allocated memory yourself, is to use an appropriate container class like std::vector<char> or std::string:

class A {
    std::string name;
};
Community
  • 1
  • 1
πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190