I am a C++ beginner. And I am doing the exercises in C++ Primer (5th Edition). I found a reference to Exercise 13.8 from Github (Here), which is shown below.
It's needed to prevent a memory leak: every new
must be balanced with a delete
.
You allocate memory for ps
with a new
in the constructors.
When you allocate memory for new_ps
and assign this to ps
, you need to free the constructor-allocated memory before you lose the old pointer value.
You program will indeed "work" if you omit that line, but it will steadily consume more and more memory, until, eventually there is no more memory left.
Note that you have another memory leak: you need to create a destructor, and call delete ps
in it.
As you can see, this is getting unduly complicated. Better still, ditch all this pointer stuff and use a std::string s
as the member variable - it takes care of all the memory management for you.