2

Imagine following scenario

I have a classes A and B

/* A class with a shared pointer */
class A {
public:
  //...

private:
  std::shared_ptr<object_t> m_ptr;
};

/* A class with an unique pointer */
class B {
public:
  //...

private:
  std::unique_ptr<object_t> m_ptr;
};

I want to have a function, which will use the object pointed by m_ptr and process it, but will not take ownership of it. Should the function take a smart pointer as an argument like

void process(std::shared_ptr<object_t> obj);

or should it use a raw pointer like

void process(object_t* obj);

Edit:

Apparently, I forgot about an important 3rd option for the function

void process(object_t& obj);

which as pointed out by kotatsuyaki should be the preferred solution.

Marco
  • 98
  • 8
  • 6
    Have you considered using references? – kotatsuyaki Jun 07 '22 at 11:44
  • Does a reference handle polymorphism? So would it call virtual functions from derived classes? – Marco Jun 07 '22 at 11:46
  • 6
    Yes, references have proper support for virtual functions. See [When to use references vs. pointers](https://stackoverflow.com/q/7058339/12122460). – kotatsuyaki Jun 07 '22 at 11:47
  • 3
    Since it does not take ownership, the parameter should **not** be a `shared_ptr`. If a `nullptr` is legitimate for the routine to handle, then `object_t*`. If a `nullptr` is not legitimate for the routine, then `object_t&`. All of them support polymorphism. – Eljay Jun 07 '22 at 11:57
  • You should never pass a shared_ptr by value like your first example unless your intention is to actually share ownership with wherever that thing is going. – Eric Jun 07 '22 at 12:04

0 Answers0