Re: Passing values by reference
On Jan 22, 12:20 pm, Juha Nieminen <nos...@thanks.invalid> wrote:
Michael DOUBEZ wrote:
magnus.morab...@gmail.com wrote:
Lets say I have the following function -
void printInt(int& i)
{
std::cout<<i;
}
must I do the following in order call it with a value -
int i = 0;
printInt(i);
is there no way to do this as a one liner?
Change your function signature to:
void printInt(const int& i)
Although the 'int' type was most probably just for the sake of
example and simplicity, I would still like to point out that
passing ints by reference rather than by value will most
probably be less efficient.
More generally, C++ uses pass by value by default, and that's
what should be used unless there is a reason to do otherwise:
-- polymorphic objects,
-- the callee modifies the object
-- (premature?) optimization
In many ways, passing even something like std::string by const
reference when you really mean value is premature optimization.
On the other hand, of course, it is so ubiquious that you would
seem wierd not to do it. (Note that if the library uses the
small string optimization, and the compiler is really, really
good, passing short std::string's by reference may actually be
more expensive than passing them 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