Auto_ptr or shared_ptr

In a C ++ 03 environment, would you use auto_ptr

or (boost) shared_ptr

to return a resource from a function? (Where in C ++ 11 it's natural to use a unique_ptr

.)

auto_ptr<T> f() {
  ...
  return new T();
}

      

or

shared_ptr<T> f() {
  ...
  return new T();
}

      

auto_ptr

has quite a few pitfalls (not least this construct is terribly buggy on MSVC 2005 , which is what I should be using), but shared_ptr

seems overkill ...

+3


source to share


3 answers


Disclaimer: This answer only applies to using auto_ptr with an implementation bug like in VS2005.

I'll add my own view after trying with help auto_ptr

in VS 2005:

I've already used auto_ptr (on this VC ++ 8) successfully in pure local contexts in the past, i.e .:

auto_ptr<T> local( ... ); // Don't use "=" to init! Will Crash on VS2005!
// use local
...
// Sometimes:
m_managing_object.setStuff( local.release() );
// Or, alternatively:
return local.release();

      

It worked well enough and the only thing that haywire could go is to use an assignment syntax for init that just crashes reliably every time, so it wasn't a big deal.

So, agreeing on the implied semantics mentioned by others, I tried to get my original example to work



auto_ptr<T> f() {
  ...
  return new T();
}
...
auto_ptr<T> pT( f() ); // or "=" init??, Variations ...
...

      

Fine!

After this trivial example, in about 1 hour 30, I still haven't figured out why and how exactly it auto_ptr

crashed every time I used this method.

I'm pretty sure this is due to a VS2005 implementation bug, i.e. I may have done something completely insane that the hopeless implementation would catch, but then it crashed and I failed.

What it means: This means that I've been using VS2005 with C ++ for over 5 years now, I'm pretty confident in debugging even the strangest scenarios, and after an hour I still haven't looked for what I did wrong. I'm sure I'll find out eventually, but if the thing is that darn easy to use, I'd rather use shared_ptr

and be done with it. Hell, even returning the original pointer is better, at least the worst you get with this is memleak (easily discoverable).

So: avoid all but the simplest auto_ptr use cases on VS2005.

0


source


In C ++ 03 I would use either a null pointer or auto_ptr

and let the caller decide on the ownership strategy.



Note that one of the pitfalls of smart pointers is that no covariance is applied to them, which means that you can override Base* f()

to Derived* f()

, but you cannot override std::x_ptr<Base> f()

to std::x_ptr<Derived> f()

; and therefore, in this case, you have no choice but to use a simple pointer.

+6


source


I would use shared_ptr

either a raw pointer because it auto_ptr

is considered a bad idea.

It really depends on your owning semantics. Who will destroy the resource he owns?

+1


source







All Articles