Why is deletion necessary in the definition of a copy statement?

I am a beginner with C ++. And I do the exercises in C ++ Primer (5th Edition). I found a link to Exercise 13.8 from Github ( here ), which is shown below.

#include <string>
#include <iostream>

using std::cout;
using std::endl;

class HasPtr {
public:
    HasPtr(const std::string &s = std::string()) : ps(new std::string(s)), i(0) { }
    HasPtr(const HasPtr &hp) : ps(new std::string(*hp.ps)), i(hp.i) { }
    HasPtr& operator=(const HasPtr &hp) {
        std::string *new_ps = new std::string(*hp.ps);
        delete ps;          // I don't know why it is needed here? 
                            // But when I delete this line, it also works.
        ps = new_ps;
        i = hp.i;
        return *this;
    }

    void print() {
        cout << *(this->ps) << endl;
        cout << this->i << endl;
    }

private:
    std::string *ps;
    int i;
};

int main() {
    HasPtr hp1("hello"), hp2("world");
    hp1.print();
    hp1 = hp2;
    cout << "After the assignment:" << endl;
    hp1.print();
}

What scares me is the function HasPtr& operator=(const HasPtr &hp). I don’t know why here delete ps;. I thought this was a mistake, but it worked when I compiled the code. However, it also works when I delete a line delete ps;. So, I do not know if delete ps;and what is the advantage if it is reserved.

+4
source share
4 answers

HasPtr::psis a dedicated heap std::string.

new HasPtr. , HasPtr::ps , delete, .

, ++ new delete . , std::unique_ptr std::shared_ptr, .

- new delete, . cppreference.com - .

, , std::string - std::string - - , .

+9

: new delete.

ps new .

new_ps ps, , .

"", , , , , .

, : delete ps .

, . , std::string s - - .

+3

.

ps = new_ps; ps, .

, ps , . , "", .

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 not been freed either
+2

++ .

, .. , , . , , , , ..

If these resources are not freed, the memory allocated for these resources will not be returned to the system. Each time your object is called, you lose a certain part of memory and during a certain period of time you would lose the main piece of memory. This is called a memory leak .

Thus, when you call delete on an object, you guarantee that the resources you freed will be freed, provided that you performed these operations in the destructor.

0
source

Source: https://habr.com/ru/post/1623245/


All Articles