Alex Rivera | Logout

Idiomatic use of std::auto_ptr or only use shared_ptr?

Asked 2008-10-13T08:56:56.480
19

Now that shared_ptr is in tr1, what do you think should happen to the use of std::auto_ptr? They both have different use cases, but all use cases of auto_ptr can be solved with shared_ptr, too. Will you abandon auto_ptr or continue to use it in cases where you want to express explicitly that only one class has ownership at any given point?

My take is that using auto_ptr can add clarity to code, precisely by adding nuance and an indication of the design of the code, but on the other hand, it add yet another subtle issue when training new programmers: they need to understand smart pointers and the fine details of how they work. When you use only one smart pointer everywhere, you can just lay down a rule 'wrap all pointers in shared_ptr' and be done with it.

What's your take on this?

Edit
Report

1 Answer

28

auto_ptr is nice in signatures, too. When a function takes an auto_ptr<T> by value, it means it will consume the T. If a function returns an auto_ptr<T>, it's clear that it relinquishes ownership. This can communicate your intents about the lifetime.

On the other hand, using scoped_ptr<T> implies that you don't want to care about the lifetime of the T. This also implies you can use it in more places. Both smart pointers are valid choices, you can certainly have both in a single program.

answered 2008-10-13T09:34:03.223

Your Answer