Sign in to follow this  
reapz

Passing const by-reference arguments problem

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
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

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this