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

前端 未结 4 1624
面向向阳花
面向向阳花 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:37

    The delete is needed to avoid a memory leak.

    The line ps = new_ps; edits the address of ps to point somewhere else.

    The memory that ps was previously pointing at still needs to be freed. The effects of removing this line are not instantly visible and the program will still 'work', but you have a memory leak.

    Eg.

    ps = address 0 with value 'f'; new_ps = address 1 with value 'g'
    Now let ps = new_ps;
    ps = address 1 with value 'g'; new_ps = address 1 with value 'g'
    So address 0 is no longer something we can access, but it's not been freed either
    

提交回复
热议问题