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:We can't change the type of the
rtodouble(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
pito change to 3 (sincerisint) just as a consequence of the reference binding.We need to create a new object by converting the
pito the type of ther. 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-
constreference 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 thepiinto anint iand change theito whatever we want.The key point for an answer to your question:
Yes, it will create an additional burden, in case of from
const char*toconst string&, but it is probably not a case of the intended use of theconst 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 likeconst string&. Well, there may be several valid reasons, and all of them will be worth having an overhead.In other cases, when a
stringis passed, you will avoid copying. Win-win situation, isn't it?