Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing std::unique_ptr to helper function

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?

like image 704
fen Avatar asked Dec 05 '22 12:12

fen


1 Answers

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).

like image 173
Konrad Rudolph Avatar answered Dec 29 '22 23:12

Konrad Rudolph