When should I pass by reference?

closed account (Ey80oG1T)
So I know passing something by reference can save time since you don't copy something, but should I pass by reference in this situation:

1
2
3
4
5
6
7
8
9
10
11
// I know this is right...

void addVector(Vector&);

Vector point1(5, 10);
addVector(point1);

// but what about this...

void subVector(Vector);
subVector(Vector(5, 10));


So if we declare a vector on the spot, do I still need a reference?
As a general rule you don't pass by reference when:
1. parameters are POD, (float, int, long etc...)
2. when parameter is smart pointer and used inside function just to access it's owning object

In almost all other cases, you pass by either reference or const reference, depends on if you want to change parameter values or not.
2. when parameter is smart pointer and used inside function just to access it's owning object

So what happens when you try to copy by value a std::unique_ptr into a function? A train wreck if you don't transfer the ownership. Copying a std::unique_ptr is not allowed.

A std::shared_ptr could be copied into a function, or passed by reference.

Using a reference no matter what the smart pointer is let's us avoid possible transfer of ownership issues.
Furry Guy, if all you do inside the function is to read owned object you should pass shared_ptr::get() or unique_tor::get() instead.

maybe I worded my self in not clear way, what I'm saying is this:
https://docs.microsoft.com/en-us/cpp/code-quality/c26415?view=vs-2019
Last edited on
Topic archived. No new replies allowed.