I have the following code
MyObject * func1() {
MyObject * obj = new MyObject();
// lots of stuff here
return obj;
}
MyObject func2() {
MyObject * obj = func1();
// even more stuff here
return *obj;
}
void main() {
MyObject obj = func2()
}
As I got it from here this code is leaking. Will this:
MyObject * func1() {
MyObject * obj = new MyObject();
// lots of stuff here
return obj;
}
MyObject func2() {
MyObject * obj = func1();
// even more stuff here
MyObject obj_r(*obj);
delete obj;
return obj_r;
}
void main() {
MyObject obj = func2()
}
resolve the issue? Or is there some other nice solutions?
in b4: no, I can’t make it reference from the beginning, as func1() returns NULL in some cases.
upd: added some comments so that people didn’t think I’m royally stupid
A more elegant solution (and more “correct”) would be to use a smart
pointer:
(With a more modern compiler, use
std::unique_ptr. Or if you’re usingBoost, you can also use
boost::scoped_ptr.)I say more “correct”, because if the copy constructor of
MyObjectthrows an exception, this solution will still delete the object, where
as yours would leak.