Why delete is needed in the definition of the copy-assignment operator?

前端 未结 4 1585
面向向阳花
面向向阳花 2021-01-13 15:09

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.



        
4条回答
  •  走了就别回头了
    2021-01-13 15:42

    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.

提交回复
热议问题