0

Normally, I like to pass parameters by references to avoid copying objects, even parameters are pointers. But I saw some developers do the following. Is there any disadvantage by doing the following?

class student {};
class teacher {};

void test(std::shared_ptr<student> student_param, teacher *teacher_param)
{
    // ...
}

int main()
{
    std::shared_ptr<student> stdnt(new student);
    std::shared_ptr<teacher> tchr(new teacher);

    test(stdnt, tchr.get())
}
O Connor
  • 4,236
  • 15
  • 50
  • 91
  • what is `test` doing? Is it a shared owner of `student_param` ? – 463035818_is_not_an_ai Dec 01 '22 at 09:10
  • 5
    Passing a shared pointer _by value_ will cause an unnecessary addref (which is an atomic operation and therefore more expensive than you'd think). It can be useful in a few cases (see https://stackoverflow.com/questions/49776400/passing-a-shared-pointer-by-reference-or-by-value-as-parameter-to-a-class/49776497#49776497). However, you should pass by `[const] student&` _unless_ you want to also take ownership of it or need it as a shared_ptr for other reasons. – Mike Vine Dec 01 '22 at 09:11
  • 1
    It's also not any more efficient (because objects with destructor are still passed by pointer, only now to a new stack-allocated temporary object). And on all major platforms except Windows, it causes code-bloat because the caller has to insert code to run the destructor for the temporary object. On Windows, that's part of the called function so it is at least not replicated everywhere – Homer512 Dec 01 '22 at 09:19
  • 3
    Unrelated: `std::shared_tr stdnt(new student)` is an antipattern. Use `auto stdnt = std::make_shared()` instead. – Botje Dec 01 '22 at 09:20
  • @463035818_is_not_a_number the `test` function gets value from and sets value to member properties of `student` and `teacher` via their getters and setters. Does this call sharing ownership? – O Connor Dec 01 '22 at 09:26
  • @MikeVine Is doing as above called passing by value? – O Connor Dec 01 '22 at 09:27
  • 2
    no it doesnt. A free function rarealy participates in ownership (unless it stores the pointer in a global or elsewhere) – 463035818_is_not_an_ai Dec 01 '22 at 09:27
  • 1
    I'd recommend using `std::unique_ptr` instead, if you can. I don't see a reason not to allocate the objects on the stack and pass them by reference. Any pointer, smart or not will increase the coplexity of the code a bit: Pointers can be null and with `std::shared_ptr` you even get the change of introducing memory leaks, if circular references are created. – fabian Dec 01 '22 at 09:40
  • 3
    If you take the shared_ptr as const ref to a shared pointer, you might just take a reference to the object itself if you do not plan to make a copy of the pointer. shared_ptr& takes as little care of making sure the object stays alive as just `student&` – Lasersköld Dec 01 '22 at 09:46

0 Answers0