Passing const by-reference arguments problem
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.
What do you mean that it would not work? Binding a literal to a const reference is perfectly legal code.
You sir are correct :) I could have sworn that has happened to me before, if it does, I'll be sure to post back.
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).
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).
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.
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement