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?

3
  • One delete[] per new[], and no need for a null check. Commented Apr 18, 2015 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<char> instead of struggling new/delete yourself. Commented Apr 18, 2015 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. Commented Apr 19, 2015 at 0:21

1 Answer 1

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;
};
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.