I have a project which I would like to make more use of smart pointers. Overall, I have been successful in this goal. However, I've come across one things which I'm not sure what the "best practice" is.
Basically I would like to return a "pointer" from a function, but require that the user hold it in a smart pointer. Not only that, I don't want to mandate a particular smart pointer (shared vs. scoped).
The problem is mostly that there doesn't seem be to a proper way to upgrade a scoped_ptr
to a shared_ptr
(that would be the ideal solution i think). I understand why they didn't do this, as it would allow transferring of ownership which can lead to some issues like those std::auto_ptr
has.
However, transferring of ownership seems like a good idea for this case. So my idea is like this:
// contrived example of factory pattern
std::auto_ptr<A> func() { return std::auto_ptr<A>(new A); }
This works "ok" since both scoped_ptr
and shared_ptr
have constructors which take ownership from a std::auto_ptr
.
So my question is, is this good practice? Is there a better solution? The only real alternative I've been able to come up with is using a template template as the return value like this:
// similar to above example
template <template <typename> class P>
P<A> func() { return P<A>(new A); }
which actually could work well except that I think it would need some work to get it to work with a scoped_ptr
too.
Thoughts?