Passing std :: unique_ptr to a helper function

Is it correct?

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?

+4
source share
3 answers

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

  void helperFunc(MyClass& my_class) { } 

call:

  helperFunc(*p); 
+5
source

If you do not want to own the memory (in this case you must pass either shared_ptr or unique_ptr ), why do you work with a pointer at all?

Follow this link.

 void helperFunc(MyClass& obj) { // do something with ptr, } unique_ptr<MyClass> p(new MyClass()); helperFunc(*p); 

Using source pointers when you don’t want to take ownership is, in general, but not necessary at all, unless you explicitly want to allow nullptr (in this case, yes, use a raw pointer).

+7
source

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

I would avoid using get() , unless helperFunc really so trivial that it does not take responsibility for the pointer and it can be guaranteed not to leak it or leave the sagging link in some other state.

If you really want to pass unique_ptr directly to a function, look at: How do I pass a unique_ptr argument to a constructor or function?

+4
source

All Articles