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

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

    In C++ programming, calling delete on a class object automatically invokes the destructor of the class.

    In general practice, destructor holds the code to free up the resources i.e file pointers,deletion of objects created inside the class.This way, when you call delete on an object,the resources it allocated are freed up i.e given back to the system

    If these resources are not freed up,the memory allocated for these resources will not be given back to the system.Every time your object gets called,you lose a certain portion of memory and over a period of time you would have lost a major chunk of memory.This is called as memory leak.

    Thus when you call delete on an object,you ensure that the resources you acquired are released, provided you have done those operations in destructor.

提交回复
热议问题