Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What type of pointer should I pass to a method in C++11?

There is two different scenarios I'm after:

  1. You have a shared_ptr
  2. You have a unique_ptr

The answer might be the same though.

Consider a method, which uses a pointer but does not assume ownership:

void use_pointer(T ptr)
{
    ptr->act();
}

Should T be

  • my_type * (raw pointer)
  • const shared_ptr<my_type> & (sending const ref, if using shared_ptr)
  • const unique_ptr<my_type> & (sending const ref, if using unique_ptr)
  • weak_ptr<my_type> (constructing weak_ptr for method call)

Something else? Thanks!

like image 952
Max Avatar asked Feb 15 '12 15:02

Max


1 Answers

If you do not assume ownership, then preferably accept a reference to the pointee. If you want to express optionality, you can use a raw pointer, or you can use e.g. boost::optional<U&> (where U is the pointee type).

Functions that do no assume ownership should almost never accept a smart pointer. There is in general nothing useful for the callee in a smart pointer interface other than means of getting to the pointee. So pass that instead.

like image 95
Luc Danton Avatar answered Oct 20 '22 16:10

Luc Danton