2

What is more common in your experience: func1() or funct2()? Assume func1 and func2 is better not as a Foo class method.

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()); }
}
Agrim Pathak
  • 3,047
  • 4
  • 27
  • 43

2 Answers2

5

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

Community
  • 1
  • 1
Ðаn
  • 10,934
  • 11
  • 59
  • 95
1

Personally I would go with mutate_bar2(). You are correctly managing the life-span of your pointer by storing it in a std::unique_ptr class member. So you don't need to worry about memory leaks. You can use the raw pointer safely. I don't see any advantage in passing round the std::unique_ptr and it is probably slightly slower to access.

Galik
  • 47,303
  • 4
  • 80
  • 117
  • This is assuming, of course, that "altering the attributes" does not involve taking a reference to `bar` for longer than the duration of the function (which is probably a reasonable assumption, in this case). If it does, you probably shouldn't be using `unique_ptr` in the first place, unless you intend to transfer ownership with `std::move()` or something. – Kevin Mar 14 '15 at 03:49
  • 1
    @Kevin Exactly. If you want the pointer to out-live the object then `std::unique_ptr` is the wrong choice to begin with. That's why I see no advantage passing the `std::unique_ptr`. – Galik Mar 14 '15 at 03:51