StackedCrooked
StackedCrooked

Reputation: 35485

Should I stop using auto_ptr?

I've recently started appreciating std::auto_ptr and now I read that it will be deprecated. I started using it for two situations:

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?

Upvotes: 14

Views: 2487

Answers (3)

Omnifarious
Omnifarious

Reputation: 56048

It is so very very useful, despite it's flaws, that I'd highly recommend just continuing to use it and switching to unique_ptr when it becomes available.

::std::unique_ptr requires 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_ptr is the best you can do.

Having both ::std::auto_ptr and ::std::unique_ptr in your code might confuse some people. But you should be able to search and replace for ::std::unique_ptr when 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_ptr with ::std::unique_tr has more details.

Upvotes: 5

jcoder
jcoder

Reputation: 30035

deprecated doesn't mean it's going away, just that there will be a better alternative.

I'd suggest keeping using it on current code, but using the new alternative on new code (New programs or modules, not small changes to current code). Consistency is important

Upvotes: 1

John Smith
John Smith

Reputation: 12797

I'd suggest you go use boost smart pointers.

Upvotes: -1

Related Questions