I've seen a similar question to this, but i'd like some clarification...
Assuming a basic C++ class:
class MyClass
{
public:
struct SomeData
{
std::wstring name;
std::vector<int> someValues;
};
void DoSomething(const SomeData data);
}
I understand that data
will be passed as const
to DoSomething
and that is ok since data
will not be modified in any way by the function...but I am used to seeing &
specified with const
parameters to ensure that they are passed by reference, e.g.
void DoSomething(const SomeData& data);
That seems more efficient to me. If we omit the &
, then isn't data
being passed by value to DoSomething
? I'm not sure why it would ever be preferable to pass a const
parameter by value when you can pass by reference and avoid the copy occurring?
Pass by value/reference and const-correctness are two different concepts. But used together.
Pass by Value
void DoSomething (SomeData data);
Pass by value is used when it is less costly to copy and do not want to keep references to foreign objects. This function could (if it is inside a class) keep a pointer to this in some case and have its own copy.
Pass by reference
void DoSomething (SomeData& data);
Always use pass by reference if you know this might cause a performance loss copying the struct. This function could (if it is inside a class) keep a pointer to this in some case and pointing to a foreign object. Keeping pointers to foreign objects mean you should aware of its life-time and when this foreign object goes out of bound. More importantly changes to foreign object appears to your pointer.
const correctness
void DoSomething (const SomeData data); // const for local copy
void DoSomething (const SomeData& data); // const for callers object
Adding const
to pass by value or reference means this function does not change it. But not having or having &
decides which object you are trying to add safety of modifying. const
is a very helpful tool in C++ in terms of Documenting APIs, provide compile time safety, allow more compiler optimizations.
Read this article.
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