Jump to content
  • Advertisement
Sign in to follow this  
reapz

Passing const by-reference arguments problem

This topic is 3355 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

For example, if I was to have a constructor: Example(const int &x, const int &y); and I called it like: Example anInstance(20, 20); It would not work, because it wants a reference to an int that goes out of scope straight away? Is there a work around to this, because it seems to be good practice to using const by-ref if its not being altered.

Share this post


Link to post
Share on other sites
Advertisement
What do you mean that it would not work? Binding a literal to a const reference is perfectly legal code.

Share this post


Link to post
Share on other sites
You sir are correct :) I could have sworn that has happened to me before, if it does, I'll be sure to post back.

Share this post


Link to post
Share on other sites
You might be thinking of non-const references - you can't pass a literal in that case.

Also, for types smaller than the CPUs word size (I.e. 32-bits or smaller on a 32-bit CPU / build), there's no real benefit to passing by const reference, and passing by value may be better (Although I'd be surprised if the compiler didn't optimise it to pass-by-value anyway).

Share this post


Link to post
Share on other sites
Quote:
Original post by Evil Steve
(Although I'd be surprised if the compiler didn't optimise it to pass-by-value anyway).

How? MSVC 2008, Release mode build default settings, compiling this code:

void (*fn1)(int);
void (*fn2)(int);

void foo(const int & x) {
(*fn1)(x);
}

void bar(int x) {
(*fn2)(x);
}

produces this assembly for bar():

push eax
call DWORD PTR ?fn2@@3P6AXH@ZA ; fn2
pop ecx

and this assembly for foo():

mov ecx, DWORD PTR [eax]
push ecx
call DWORD PTR ?fn1@@3P6AXH@ZA ; fn1
pop ecx

Note the added instruction for the dereference.

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!