Solved Need an advice with pointer
-
Hi! I typed a short simple code... Is there a good way to avoid memory leak in case of 'return'?
I don't want to 'delete mstr' in each 'return' statement.void my_func(){ my_struct *mstr = new my_struct; if(!check1()) return; mstr->val1 = val1; if(!check2()) return; mstr->val2 = val2; my_vector.push_bach(mstr); }
-
@sitesv said in Need an advice with pointer:
I don't want to 'delete mstr' in each 'return' statement.
use smart pointers:
-
Hi,
Or do both checks before and return early since if any of the two fails you do not add anything to your vector.
-
@KroMignon said in Need an advice with pointer:
use smart pointers:
But how to be if pointer was added to the vector? (in case of smart pointers)
-
@sitesv said in Need an advice with pointer:
But how to be if pointer was added to the vector? (in case of smart pointers)
You could use
std::unique_ptr<>()
or Qt equivalentQScopedPointer<>()
:void my_func(){ auto mstr = std::unique_ptr<my_struct>(new my_struct); //auto mstr = QScopedPointer<my_struct>(new my_struct); if(!check1()) return; mstr->val1 = val1; if(!check2()) return; mstr->val2 = val2; // convert smart pointer back to raw pointer my_vector.push_back(mstr.release()); //=> for QScopedPointer my_vector.push_back(mstr.take()); }
-
@KroMignon
Big thanks to you! -
A version without useless memory allocation:
void my_func() { if (!check1() || !check2()) { return; } my_struct *mstr = new my_struct; mstr->val1 = val1; mstr->val2 = val2; my_vector.push_back(mstr); }
It can even be shorter if my_struct has a constructor.