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?
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?
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 nullptr
s (in which case, yes, use a raw pointer).
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);
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?