通过 unique_ptr vs raw_ptr?

Passing unique_ptr vs raw_ptr?

根据您的经验,哪个更常见:func1() 或 funct2()?假设 func1 和 func2 最好不要作为 Foo class 方法。

void func1(unique_ptr<Bar>& bar) { /* alter pointed to object's attributes */ }

void func2(Bar* const bar) { /* alter pointed to object's attributes */ }

class Foo
{
  unique_ptr<Bar> bar;
  void mutate_bar1(){ func1(bar); }
  void mutate_bar2(){ func2(bar.get()); }
}

就我个人而言,我会选择 mutate_bar2()。您通过将指针存储在 std::unique_ptr class 成员中来正确管理指针的寿命。所以你不需要担心内存泄漏。您可以安全地使用原始指针。我看不出绕过 std::unique_ptr 有什么好处,访问速度可能稍慢。

来自GotW #91 Solution: Smart Pointer Parameters

Guideline: Don’t pass a smart pointer as a function parameter unless you want to use or manipulate the smart pointer itself, such as to share or transfer ownership.

Guideline: Prefer passing objects by value, *, or &, not by smart pointer.


As usual, use a * if you need to express null (no widget), otherwise prefer to use a &; and if the object is input-only, write const widget* or const widget&.