4

Is this a proper way?

void helperFunc(MyClass *ptr)
{
    // do something with ptr,
}

unique_ptr<MyClass> p(new MyClass());
helperFunc(p.get());

or should I use shared_ptr for such operations?

billz
  • 41,716
  • 7
  • 75
  • 95
fen
  • 8,812
  • 5
  • 29
  • 53

3 Answers3

7

Unless you want to take ownership of the memory (in which case you should pass either a shared_ptr or a unique_ptr), why are you working with a pointer at all?

Pass by reference.

void helperFunc(MyClass& obj)
{
    // do something with ptr,
}

unique_ptr<MyClass> p(new MyClass());
helperFunc(*p);

Using raw pointers when you don’t want to take ownership is fine in general but unnecessary here, unless you explicitly want to allow nullptrs (in which case, yes, use a raw pointer).

Konrad Rudolph
  • 482,603
  • 120
  • 884
  • 1,141
5

If helpFunc takes the ownership you pass std::shared_ptr or std::unique_ptr otherwise just pass by reference:

  void helperFunc(MyClass& my_class)
  {
  }

call:

 helperFunc(*p);
R. Martinho Fernandes
  • 209,766
  • 68
  • 412
  • 492
billz
  • 41,716
  • 7
  • 75
  • 95
  • 5
    This is silly. If the function doesn't want to take ownership *why the heck is ownership* (i.e. unique_ptr) *even in the interface*? The way to take non-owning references has always been to take MyClass& or MyClass* or const variants. *That has no reason to change now*. – R. Martinho Fernandes Feb 01 '13 at 10:58
  • The only potential issue with raw pointers is if you work with an application that mixes libs supporting smart pointers (and using them consistently) and libraries that are not using them (because they target an older standard). In such a case, you might find yourself with similar raw-pointer functions that may or may not take ownership. See my blog post on [unique_ptr usage](http://wp.me/p2Bia3-2U) – TiMoch Apr 13 '13 at 20:00
4

When you use the get() functions, you get a raw pointer and lose the allocation-tracking that you're using the unique_ptr class to have in the first place.

I would avoid using get(), unless helperFunc really is so trivial that it does not take ownership of the pointer, and can be guaranteed not to leak it or leave a dangling reference in some other state.

If you really mean to pass the unique_ptr itself to the function, take a look at: How do I pass a unique_ptr argument to a constructor or a function?

Community
  • 1
  • 1
sheu
  • 5,291
  • 15
  • 29
  • yes, I assume helperFunc does not need "full" ownership... but that way I leave door open for some troubles in the future. – fen Feb 01 '13 at 10:37
  • @fen: yes that very much leaves potential for future trouble. – sheu Feb 01 '13 at 10:38