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?

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

Comments

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

2 Comments

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

2 Comments

yes, I assume helperFunc does not need "full" ownership... but that way I leave door open for some troubles in the future.
@fen: yes that very much leaves potential for future trouble.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.