Jump to content
  • Advertisement
Sign in to follow this  
wicked357

Just curious about this...

This topic is 2947 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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.

Share this post


Link to post
Share on other sites
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?

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!