Re: Const String References
AJ wrote:
Not entirely sure what the cost difference between these is:
#include <string>
using namespace std;
void foo(char* s) {
const string bar1 = s;
const string& bar2 = s;
const string bar3(s);
const string& bar4(s);
}
I doubt that there is any.
I believe 1 is identical to 3
1 and 3 are definitly not identical formally---1 requires the
use of the copy constructor, where 3 doesn't allow it. But
there is a special provision in the standard that allows the
compiler to skip the extra copy in 1, regardless, and I've never
heard of a compiler which didn't do it. (On the other hand, if
you have a type without an accessible copy constructor, 1 is
illegal.)
and 2 to 4 (simply different syntax).
I think that this is true. According to the standard, reference
initialization is copy initialization when the initialization
expression is not of the correct type. As with copy
initialization, you formally have an additional copy (and the
copy constructor must be accessible), but in practice, all
compilers optimize it out.
But I don't understand how many copies/strlens 1 and 3 create
vs. 2 and 4.
Same number of strlen, in any case. In case 3, you're
guaranteed that there are no additional copies; in the other
cases, there could be, at least in theory.
--
James Kanze (GABI Software) email:james.kanze@gmail.com
Conseils en informatique orient?e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S?mard, 78210 St.-Cyr-l'?cole, France, +33 (0)1 30 23 00 34
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]