There are many existing questions about const
reference (reference to const). But when there is an implicit conversion, const
reference also causes a new address. I wrote this example bellow:
int i = 42;
double d = 4.2;
const int& ri1 = i;
const int& ri2 = d;
&ri1
and &i
would print the same address, however &ri2
and &d
are different. What's the object that ri2
really serves for? As "C++ Primer" says, it generates a temporary object. But if the converted const reference uses the difference address, that means this address still has a valid object.
Suppose I have a big long string
or const char*
as "long example text" and pass it to some function that accepts const string&
, there would be the similar conversion.
It is helpful to think this way:
We would not want to bind a (plain) &
reference to an object if this binding will cause this object to change. E.g. from 3.1415 to 3, like here:
double pi = 3.1415;
int& r = pi; // Imagine, now both r and pi are 3...
We can't change the type of the r
to double
(otherwise, that would be quite a logic for the language!).
And I'm sure most of the C++ users would not want to have the value of the referred to pi
to change to 3 (since r
is int
) just as a consequence of the reference binding.
We need to create a new object by converting the pi
to the type of the r
. When we have a conversion happened, the reference will be bind to a temporary object created as a result of this conversion.
There will be no reason to have a non-const
reference to this unnamed object to which we have no other (except for the reference "handle") access. If we some reason would like it to change, we could just copy the pi
into an int i
and change the i
to whatever we want.
Yes, it will create an additional burden, in case of from const char*
to const string&
, but it is probably not a case of the intended use of the const string&
.
Why? Because if you know for sure that, say, your function will be passed a const char*
(and only it) and that you can't afford any overhead whatsoever, why would you declare a parameter like const string&
. Well, there may be several valid reasons, and all of them will be worth having an overhead.
In other cases, when a string
is passed, you will avoid copying. Win-win situation, isn't it?