Proper use of the destructor

I just started working with C ++, and now I have a really basic question.

I wrote 2 classes:

coordinates:

#include <stdio.h>

class Coordinate {
private:
    int x;
    int y;
public:
    Coordinate(int a, int b) {
        x = a;
        y = b;
    };
    void printTest() {
        printf("%d %d\n", x, y);
    };
};

Test:

class Test {
private:
    int q;
    Coordinate *point;
public:
    Test(int a, int b, int c) {
        q = a;
        point = new Coordinate(b, c);
    };
    virtual ~Test() {
        delete point;
    }
};

The main function:

int main() {
    Test *test = new Test(1, 2, 3);
    // ...
    delete test;
    return 0;
}

In mine, mainI worked with a class object Test. I wrote my own destructor Test, but I'm not sure if this destructor works as expected. Does this completely free memory from Test? Or do I need to do something with an attribute qin order to free it?

+4
source share
4 answers

Yes, this is the correct use of the C ++ destructor (your destructor in Test does not need a key virtual, since there is no inheritance in your example).

, new delete, , , . , , , , , !

, delete test, point, , , . (yay!), :)

+4

, , , . Valgrind

==28151== HEAP SUMMARY:
==28151==     in use at exit: 0 bytes in 0 blocks
==28151==   total heap usage: 3 allocs, 3 frees, 72,736 bytes allocated
==28151== 
==28151== All heap blocks were freed -- no leaks are possible

, , . , "", , Test, , . , .

, C++ " " " " , , Rule of Zero, , new delete, , .

+9

, , . ( " " ). , .

, : // ... , :

Test testB = *test;

testB Coordinate, , *test. , , testB , , *test.

:

Test(const Test& other)
    : point (new Coordinate(other.x, other.y))
    , q(other.q)
{

}

, Coordinate* .

+1
source

In your case you don't need a pointer

class Test {
private:
    int q;
    Coordinate point;
public:
    Test(int a, int b, int c) : q(a), point(b, c) {};
};

int main() {
    Test test(1, 2, 3);
    // ...
    return 0;
}

It would be enough.

If you want to allocate memory, I highly recommend using a smart pointer or container instead:

class Test {
private:
    int q;
    std::unique_ptr<Coordinate> point;
public:
    Test(int a, int b, int c) : q(a), point(std::make_unique_ptr<Coordinate>(b, c)) {};
};

int main() {
    auto test = std::make_unique<Test>(1, 2, 3);
    // ...
    return 0;
}

In both cases, you respect rule 3/5/0.

In the second case, you probably need to provide a copy constructor for your class:

Test(const Test& rhs) : q(rhs.q), point(std::make_unique<Coordinate>(*rhs.point)) {}
0
source

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


All Articles