Re: why should one use "&" in "const char*const& szString"
On Feb 23, 4:39 pm, Jeff Schwab <j...@schwabcenter.com> wrote:
Victor Bazarov wrote:
alariq wrote:
Can some one explain me why should one use this construction. Is there
any need for "&" ?
Is there any difference between those 2 options: (excluding that in
first case *szString is passed by value and in second - by reference):
1) const char*const& szString
2) const char*const szString
Actually, it's vice versa - in the first case it's passed by
reference and in the second - by value. But you're correct
it doesn't really make much of a difference. A *possible*
(yet unlikely) reason is that they wanted to make some kind
of obscure overloading work or pick some particular
template... Or did it simply out of habit (more likely).
In addition to what Victor said, it's worth noting that the
pass-by-reference overload may be slower, especially if the
function's definition has not yet been seen by the compiler at
the point of call. The problem is that the pass-by-reference
overload is allowed to retain a pointer to its argument (thus
restricting possible optimizations), whereas the pass-by-value
version is not.
In practice, the pass by reference is always implemented by
passing a pointer. Which means that the object referred to must
be locked in memory. For simple objects, which could otherwise
be in a register, this can make a significant difference; if a
function takes an int const&, and I pass it 43, the compiler
must create a temporary value (in memory) of type int,
iniitialize it with 43, then take the address of this variable
and pass it. If I just declare the function to take an int (or
an int const), the compiler can just pass the value immediately.
Within the called function, of course, the compiler must take
into account that the reference might be an alias; i.e. that
other references might refer to it, or that it might refer to a
global variable. This can lead to a lot more memory accesses
than otherwise.
In theory, the above should apply to any "smallish" type,
including non-polymorphic class types which only require one or
two words. In practice, I'm not aware of any compiler which
manages to optimize such objects into registers when they have
user defined constructors, so passing by const reference will
usually result in one copy less, with no other real effects, at
the call site. (The issues concerning aliasing still affect the
called function, however.) For this reason, one common
convention is to pass class types by reference to const, and
everything else by value.
--
James Kanze (GABI Software) email:james.kanze@gmail.com
Conseils en informatique orient=E9e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S=E9mard, 78210 St.-Cyr-l'=C9cole, France, +33 (0)1 30 23 00 34