I have always been taught that non-primitive types should be passed by const reference rather than by value where possible, ie:
void foo(std::string str);//bad
void foo(const std::string &str);//good
But I was thinking today that maybe actually some simple user defined types may actually be better passed by value eg:
class Vector2
{
public:
float x, y;
...constructors, operators overloads, utility methods, etc...
};
void foo(Vector2 pos);
void foo(const Vector2 &pos);//is this really better than by value?
void foo(float x, float y);//after all isn't by value effectively doing this?
My thought is that by passing the Vector2 by reference, it is actually more expensive than passing by value since the compiler is now using a pointer and dereferencing to access the const Vector2 &pos version?
Is this the case? Are simple objects best off passed by value? Where should the line be drawn?
So, frequently, you can pass string_view by reference and get away with it. But you should pass string_view by value, so that the compiler doesn't have to do those heroics on your behalf. And so that your code-reviewer doesn't have to burn brain cells pondering your unidiomatic decision to pass by reference.
Pass Using Const Reference in C++ Now, we can use the const reference when we do not want any memory waste and do not change the variable's value. The above code will throw a compile error as num = num +10 is passed as a const reference.
No. A reference is simply an alias for an existing object.
The const keyword in front of the object name is used to guarantee that your function does not modify the objects that are passed to the function by reference or pointer. Not only will this tell other programmers that your function is safe to use, it is also strictly enforced by the compiler.
Yes, simple objects should be passed by value. The line has to be drawn according to the architecture. If in doubt, profile.
Just as a matter of policy I pass any object that isn't a basic C data type by const reference. Its much easier to remember that way.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With