I’ve recently started appreciating std::auto_ptr and now I read that it will be deprecated. I started using it for two situations:
- Return value of a factory
- Communicating ownership transfer
Examples:
// Exception safe and makes it clear that the caller has ownership.
std::auto_ptr<Component> ComponentFactory::Create() { ... }
// The receiving method/function takes ownership of the pointer. Zero ambiguity.
void setValue(std::auto_ptr<Value> inValue);
Despite the problematic copy semantics I find auto_ptr useful. And there doesn’t seem to be an alternative for the above examples.
Should I just keep using it and later switch to std::unique_ptr? Or is it to be avoided?
It is so very very useful, despite it’s flaws, that I’d highly recommend just continuing to use it and switching to
unique_ptrwhen it becomes available.::std::unique_ptrrequires a compiler that supports rvalue references which are part of the C++0x draft standard, and it will take a little while for there to be really wide support for it. And until rvalue references are available,::std::auto_ptris the best you can do.Having both
::std::auto_ptrand::std::unique_ptrin your code might confuse some people. But you should be able to search and replace for::std::unique_ptrwhen you decide to change it. You may get compiler errors if you do that, but they should be easily fixable. The top rated answer to this question about replacing::std::auto_ptrwith::std::unique_trhas more details.