Reputation: 11915
I have a function that allocates memory using the new
keyword.
That array gets returned from the function, but I need to somehow free it. Is it ever freed after the function returns, or is it up to the receiving code to free the array after it is done with it?
Should I just make this array a member variable, and free it in the class destructor?
Upvotes: 0
Views: 809
Reputation: 64203
Take a look at boost::shared_array. It does what you need. Either that, or use std::vector
Upvotes: 0
Reputation: 25271
If you allocate memory explicitly with new
, you must free it explicitly with delete
. Local variables will be freed upon return; classes like vector
may do some allocation behind the scenes but they will clean that up for you.
In general, C++ largely lets you pick your memory management model. You can stick with locals and non-pointer class members and get scope-based allocation. You can play with pointers and malloc/free or new/delete (but never free() a new'd pointer and vice versa!). Or, you could grab Boost and get boost::shared_ptr
for reference counting semantics.
Upvotes: 5
Reputation: 263078
Should I just make this array a member variable, and free it in the class deconstructor?
That's generally a very good idea, but why reinvent the wheel? Just use std::vector<T>
.
Upvotes: 3
Reputation: 26060
It depends. You need to define who has got the ownership of such object.
You can allocate the array in your function, return it, and let the caller free it, or put a pointer to it in a class which will destroy the pointer in the destructor.
If the ownership for such object should be shared among many entities you should use something like a shared_ptr
.
I'd also suggest to always use some kind of smart pointer to handle your raw pointers.
Upvotes: 2