Don’t try to write Java in C++, write C++ and forget how you did it in Java. Writing the right way works and there are no leaks. There’s no reason why this code could produce a 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;
}
Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.
If you want to do what you shouldn’t do in this case, you can do smart pointers, which is the right way to deal with memory management in the 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;
}
Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.
yes , but in this case I want to create the obj in function and allocate it in heap and return to dstruir with delete
– dougllas
Did the answer solve your question? Do you think you can accept it? See [tour] if you don’t know how you do it. This would help a lot to indicate that the solution was useful for you. You can also vote on any question or answer you find useful on the entire site (when you have 15 points).
– Maniero