I’m quite new to smart pointers and was trying to refactor some existing code to use auto_ptr. The question I have is about double pointers and their auto_ptr equivalent, if that makes sense.
I have a function that accepts a double pointer as its parameter and the function allocates resources for it:
void foo ( Image** img ) { ... *img = new Image(); ...}
This function is then used like this:
Image* img = NULL;
foo ( &img );
...
delete img;
I want to use auto_ptr to avoid having to call delete explicitly. Is the following correct?
void foo ( auto_ptr<Image>* img ) { ... *img = auto_ptr<Image>(new Image()); ...}
and then
auto_ptr<Image> img = NULL;
foo ( &img );
Thanks.
std::auto_ptr<>has weird copy semantics (actually it’s move semantics, rather than copy semantics) and is often not what you want when you want a smart pointer. For example, it cannot be put into STL containers.If your standard library comes with TR1 support, use
std::tr1::shared_ptr<>instead. (If it doesn’t, use boost’sboost::shared_ptr<>, which is whatstd::tr1::shared_ptr<>was taken from.)If you want to stick with
std::auto_ptr<>for your code, you can pass it into the function per non-constreference:Or you could just return the pointer: