Just curious about this...

Started by
5 comments, last by cgrant 13 years, 9 months ago
I have been curious about this for quite some time and I am not to cocky to ask such a basic question. I just have often seen this in peoples source and wondered why exactly they do this,

void function(const int& x, const int& y)
{
}

instead of just this,

void function(int x, int y)
{
}

Anyone wanna explain why one over the other exactly? Thanks in advance.
Advertisement
I may be wrong but I believe the first function doesn't need to create copies whereas the other one does. I guess this results in it being maybe a little bit faster and ?use less memory?

Yo dawg, don't even trip.

Pass-by-value vs Pass-by-reference, check those terms out. The const simply ensures that the value passed into the function isn't mutated.
Thats correct. The top example is a past by reference and its also putting on the const constraints so that you can't modify the params to easy. Since it is by reference, it is using the actual memory location of where the data was being passed from and not creating a copy. The second, makes a copy of the variables passed though (and implicitly calls the copy constructor?). I would hardly call this much overhead on primitive data types but you will notice it on more complex structures.
Thanks for the quick responses, I get it now, I wasn't thinking in terms of memory at all, good to know.
There's no point doing this on primitive types like ints though - they're practically free to copy. You definately want to do this on more complex types though, like std::string, because copying one involves quite a lot of work.
Like Hodgman said its pointless to pass primitive types as reference, since its a reference is essentially a pointer which based on architecture is usually the size of the primitive anyways. So passing an int as a reference on a 32-bit system is doesn't really save you anything much since pointers on a 32-bit system are 32 bit in size and an int is 32bit in size. This only applies to const reference though since the const qualifier makes the parameter immutable.

This topic is closed to new replies.

Advertisement