auto_ptr或shared_ptr

Mar*_* Ba 3 c++ auto-ptr shared-ptr visual-c++-2005

在C++ 03环境中,您是否会使用a auto_ptr或(boost)shared_ptr从函数返回资源?(在C++ 11中,人们自然会使用unique_ptr.)

auto_ptr<T> f() {
  ...
  return new T();
}
Run Code Online (Sandbox Code Playgroud)

要么

shared_ptr<T> f() {
  ...
  return new T();
}
Run Code Online (Sandbox Code Playgroud)

auto_ptr有一些陷阱(至少它的构造在MSVC 2005上非常错误的,这是我必须使用的),但shared_ptr似乎有点过分......

Mat*_* M. 6

在C++ 03中,我会使用一个裸指针或一个auto_ptr让调用者决定所有权策略.

需要注意的是智能指针的缺陷之一是,协方差并不适用于他们,这意味着你可以覆盖Base* f()Derived* f(),但你不能覆盖std::x_ptr<Base> f()std::x_ptr<Derived> f(); 因此在这种情况下,您别无选择,只能使用简单的指针.