Re: need help on coding grammar about reference / pointer /instance.
On 2006-05-27 19:19, Steve Pope wrote:
Erik WikstrFm <Erik-wikstrom@telia.com> wrote:
If I understand you correctly what you are asking for is something lika
this:
// Using a pointer
FooClass::foo(string* s)
{
srt = *s;
}
// Using a reference
FooClass::foo(string& s)
{
str = s;
}
// Using a copy
FooClass::foo(string s)
{
str = s;
}
Whenever possible it is preferable to use a reference instead of a
pointer, and often instead of using a copy too.
Okay, this is a point of C++ style I don't understand. (One of
many, I expect.) Why would one use a reference argument to a
function, unless one wanted the function to modify the referent?
I frequently see this in people's code. Is a copy argument
less efficient? (Seems unlikely to me.)
A copy can be very inefficient if the object passed is large, in that
case it's better to pass a const reference, since you then don't have to
copy the object. Imagine for example passing a collection (vector, list
etc.) as a copy, with many objects in the collection the operation will
be very slow compared with a reference.
Erik WikstrFm
--
"I have always wished for my computer to be as easy to use as my
telephone; my wish has come true because I can no longer figure
out how to use my telephone" -- Bjarne Stroustrup