Avoid leakage of memory as a function of return

0

You have an exercise in the C ++ workbook that asks you to create a function that returns an object by preventing memory leakage. I did so but I'm not sure if it really works:

class Point1{
    public : int x;
    public : int y;

    Point1(int x,  int y  );
    ~Point1();
};

Point1::Point1( int x1,  int y1    ){
this->x=x1;
y=y1;
std::cout <<"oioi"<<std::endl  ;
}

Point1::~Point1(){
    std::cout <<"destruu"<<std::endl ;

}

Point1 * retorno(){

     Point1* C = new Point1(1,4);

     cout<< endl;
     return C;
}

int main() {


     Point1*C=retorno();

     cout << C ;
     cout<< endl;
     cout<< endl;
     cout<< C->x;

    return 0;
}
    
asked by anonymous 03.01.2017 / 17:18

1 answer

1

Do not try to write Java in C ++, write C ++ and forget how you did in Java. Writing the right way works and there are no leaks. You do not have to cause this code to leak.

#include <iostream>
using namespace std;

class Point1 {
public:
    int x;
    int y;

    Point1(int x, int y);
    ~Point1();
};

Point1::Point1(int x1, int y1) {
    x = x1;
    y = y1;
    cout << "criou" << endl; //estou deixando só para fins didáticos
}

Point1::~Point1() {
    cout << "destruiu " << x << " " << y << endl; //para fins de debug
}

int main() {
    Point1 C(1, 4);
    cout << C.x << endl;
    cout << C.y << endl;
}

See working on ideone .

If you want to do what you should not do in this case, you can do with smart pointers , which is the correct way to handle memory management in heap .

#include <iostream>
#include <memory>
using namespace std;

class Point1 {
public:
    int x;
    int y;

    Point1(int x, int y);
    ~Point1();
};

Point1::Point1(int x1, int y1) {
    x = x1;
    y = y1;
    cout << "criou" << endl; //estou deixando só para fins didáticos
}

Point1::~Point1() {
    cout << "destruiu " << x << " " << y << endl; //para fins de debug
}

unique_ptr<Point1> retorno() {
    unique_ptr<Point1> C(new Point1(1,4));
    return C;
}

int main() {
    auto C = retorno();
    cout << C->x << endl;
    cout << C->y << endl;
}

See running on ideone .

    
03.01.2017 / 18:17