Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ...

like image 881
Martin Ba Avatar asked Aug 04 '26 12:08

Martin Ba


2 Answers

In C++03, I would use either a bare pointer or an auto_ptr and let the caller decide on the ownership strategy.

Note that one of the pitfalls of smart pointers is that covariance does not apply to them, meaning that you can override Base* f() by Derived* f() but you cannot override std::x_ptr<Base> f() by std::x_ptr<Derived> f(); and thus in this case you have no choice but to use a simple pointer.

like image 65
Matthieu M. Avatar answered Aug 07 '26 03:08

Matthieu M.


I would use a shared_ptr or a raw pointer because auto_ptr is considered a bad idea.

It really depends on your ownership semantics. Who will destroy the owned resource?

like image 39
Tony The Lion Avatar answered Aug 07 '26 03:08

Tony The Lion