c++shared-ptrauto-ptrvisual-c++-2005

auto_ptr or shared_ptr


In a C++03 environment, would you use an auto_ptr or a (boost) shared_ptr to return a resource from a function? (Where in C++11 one would naturally use a unique_ptr.)

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

or

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

auto_ptr has quite some pitfalls (not the least that it's construction is awfully buggy on MSVC 2005 which is what I have to use), but shared_ptr seems like overkill ...


Solution

  • Disclaimer: This answer purely is applicable to auto_ptr use with a buggy implementation like the one in VS2005.

    I will add my own view after trying with auto_ptr on VS 2005:

    I have already used auto_ptr (on this VC++8) successfully in pure local contexts in the past, that is:

    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();
    

    This worked well enough, and the only thing that could go haywire was using assignment syntax for init, which just reliably crashes every time so it wasn't a big deal.

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

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

    Fail!

    After fiddling with this trivial example for about 1h30, I still didn't find out why and how exactly auto_ptr crashed every time when used this way.

    I'm pretty sure that this is due to the buggy implementation of VS2005, that is, I may have done something completely bonkers that a bug-free implementation would've caught but here it crashed and I failed to get it right.

    What does this mean: It means I'm using VS2005 with C++ for over 5 years now, I'm pretty confident at debugging even the weirdest scenarios, and after over an hour I still hadn't fiddled out what I did wrong. I'm sure I'd have found out eventually, but if an thing is so damn easy to misuse, I'd rather use shared_ptr and be done with it. Hell, even a raw pointer return is better, at least the worst thing you'll get with that is a memleak (easily detectable one).

    So: Stay clear of all but the most trivial use cases of auto_ptr on VS2005.