Smart pointer library in boost
Suppose I have this function in c++: int* f(int size) { int * array = new int[size]; return array; } Is there a safe idiom to prevent memory leak? Should i use auto_ptr in C++? Or should I use the smart pointer library in boost? Which is the simplest solution? Thank you.
Olga Gerchikov wrote:
Suppose I have this function in c++:
int* f(int size) { int * array = new int[size]; return array;
}
Is there a safe idiom to prevent memory leak?
yes.
Should i use auto_ptr in C++?
yes, but not here.
Or should I use the smart pointer library in boost? Which is the simplest solution?
use std::vector<int> in the above case: std::vector<int> v( size ); -Thorsten
Olga Gerchikov wrote:
Is there a safe idiom to prevent memory leak? Should i use auto_ptr in C++? Or should I use the smart pointer library in boost? Which is the simplest solution?
Using a smart pointer will prevent the leak. Which smart pointer depends on your requirements. If you KNOW you only need it in the calling scope, use boost::scoped_array. Otherwise use boost::shared_array. std::auto_ptr is not applicable because it can only handle pointers allocated with new, not those allocated with new[]. Sebastian Redl
participants (3)
-
Olga Gerchikov
-
Sebastian Redl
-
Thorsten Ottosen