How can I change an std::auto_ptr to a boost::shared_ptr? Here are my restrictions: 1. I am using an API class, lets call it only_auto that returns these pointers 2. I need to use the call in auto_only 3. My semantics involves sharing so I do need to use a shared_ptr) 4. In class only_auto operator = is private to prevent coping 5. Also a only_auto object must be made by a cloning call std::auto_ptr creat_only_auto();
I know of template explicit shared_ptr(std::auto_ptr & r); but how do I use it in this scenario?
A super-simplified code example:
#include <iostream>
#include <memory>
#include <boost/shared_ptr.hpp>
using namespace std;
class only_auto
{
public:
static auto_ptr<only_auto> create_only_auto();
void func1();
void func2();
//and lots more functionality
private:
only_auto& operator = (const only_auto& src);
};
class sharing_is_good : public only_auto
{
static boost::shared_ptr<only_auto> create_only_auto()
{
return boost::shared_ptr (only_auto::create_only_auto()); //not the correct call but ...
}
};
int main ()
{
sharing_is_good x;
x.func1();
}
Most valid uses of auto_ptr are source compatible with std::unique_ptr, so you might want to look at converting to that. If everything builds okay then you're safe. (You might want to move to using a typedef if you're not already, so you can easily change the type in the future.) If you have a compile error you may have a bug in your code where you were previously using an invalidated auto_ptr.
I think you should only look to moving to std::shared_ptr after you've validated things with unique_ptr and you see you really do need shared ownership (often you can just use unique ownership and non-owning pointers).