473,326 Members | 2,136 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,326 software developers and data experts.

Pointer and reference

There are two situations under which I am not sure which one to use, pointer
or reference:

Passing parameter into a function
A object is aggregated in another one.

Is there any general rules of thumb about this?

Many thanks!
Jul 22 '05 #1
3 1321
dover wrote:
There are two situations under which I am not sure which one to use, pointer or reference:

Passing parameter into a function
A object is aggregated in another one.

Is there any general rules of thumb about this?


Always use the weakest construction you can.

Use delegation unless you must inherit. Use 'double' unless you need 'float'
(the latter are more work for modern CPUs). Use private members without
Get() and Set() methods unless other classes have a legitimate reason to see
or change them. Put classes in the .cpp file unless you must share them
between other translation units.

Use references unless you must use a pointer. Pointers can re-seat, can
iterate an array, and can contain NULL, and cannot easily point to a
temporary.

That last point needs more explainations. Constant references can cause
invisible objects to exist.

The C++ keyword const implies (and sometimes enforces) a variable cannot
change its value. C++ functions can take arguments by copy, by address, or
by reference. Ideally, if an object passed into a function does not change,
the object should pass by copy:

void foo(SimCity aCity);

That code is inefficient. In general, programmers should not stress about
efficiency until they have enough code to measure it and find the slow
spots. In this situation, a more efficient implementation is equal cost.
When we pass by reference, our program spends no time making a huge copy of
an entire city:

void foo(SimCity &aCity);

Now if foo() won't change that city's value, the function should declare
that intention in its interface, using pass-by-constant-reference to
simulate pass-by-copy:

void foo(SimCity const &aCity);

That is the most efficient call syntax, cognitively and physically. It's
cognitively efficient because it gives foo() no copied object to foolishly
change and then discard. Statements inside foo() that might attempt to
change that city shouldn't compile. It's physically efficient because the
compiler produces opcodes that only give foo() a handle to an existing city,
without copying it.

C++ supports qualifications before their qualified types, such as "const
SimCity &". I try to write expressions with the most important part first.
There are also subtle technical reasons, in rare situations, to write
"SimCity const &", with the const after its type.

Now imagine if we call foo(1001). That works if SimCity has a constructor
that takes an integer:

class SimCity { public:
SimCity (int population);
....
};

Inside foo(), this works:

void foo(SimCity const &aCity)
{
Alien aAlien;
anAlien.abduct(aCity, 10);
}

Now, from what city did the alien abduct 10 citizens? Between foo(1001) and
aCity is an invisible temporary object. Only constant references can summon
such cities, out of thin air.

Spooky.

--
Phlip
http://industrialxp.org/community/bi...UserInterfaces
Jul 22 '05 #2
dover posted:
There are two situations under which I am not sure which one to use, pointer or reference:

Passing parameter into a function
A object is aggregated in another one.

Is there any general rules of thumb about this?

Many thanks!

Yes there is: Use a reference.
Upon failure of that method, use a pointer.
void Cheese(int& k)
{
k *= 3 + k;
}
void Squeeze(char* kra)
{
kra[0] = 'K';
kra[7] = 't';
}

void Squeeze(char& kra)
{
(&kra)[0] = 'K';
(&kra)[7] = 't';
}

int main()
{
int monkey = 7;

Cheese(monkey);

char blah[] = "Chocolate squirrel";

Squeeze(blah)

Squeeze(blah[0]);
}
Obviously, for "Cheese", the reference is what you want.

For "Squeeze", you'll want a pointer, although a reference
will also do the job, just not as eloquently.
-JKop
Jul 22 '05 #3
"Phlip" <ph*******@yahoo.com> wrote...
[...]
Now imagine if we call foo(1001). That works if SimCity has a constructor
that takes an integer:

class SimCity { public:
SimCity (int population);
....
};

Inside foo(), this works:

void foo(SimCity const &aCity)
{
Alien aAlien;
anAlien.abduct(aCity, 10);
Curiously, aliens should actually abduct copies, otherwise [logically]
the 'aCity' has to be non-const if we expect its population to decrease
by 10 as a result of alien abduction.

Just a thought...
}

Now, from what city did the alien abduct 10 citizens? Between foo(1001) and aCity is an invisible temporary object. Only constant references can summon such cities, out of thin air.

Spooky.


There is still a big question whether the aliens did in fact abduct any
citizens. If the temporary object is const inside 'foo', its population
hasn't really changed. Yet a local alien managed to get away with ten
of something. That's spooky.

:-)
Jul 22 '05 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

110
by: Mr A | last post by:
Hi! I've been thinking about passing parameteras using references instead of pointers in order to emphasize that the parameter must be an object. Exemple: void func(Objec& object); //object...
9
by: Sandy | last post by:
Hi, In one of my interview I was asked a question, whether using pointers for argument is efficient then reference or not. i.e. void fun(Complex *p) void fun(Complex &ref) can somebody...
18
by: man | last post by:
can any one please tell me what is the diff between pointer and reference.....and which one is better to use ....and why???????
12
by: Mike | last post by:
Consider the following code: """ struct person { char *name; int age; }; typedef struct person* StructType;
13
by: al.cpwn | last post by:
I get that these two are different int* get() { static int m; return &m; } int& get() {
51
by: Kuku | last post by:
What is the difference between a reference and a pointer?
8
by: toton | last post by:
HI, One more small doubt from today's mail. I have certain function which returns a pointer (sometimes a const pointer from a const member function). And certain member function needs reference...
33
by: Ney André de Mello Zunino | last post by:
Hello. I have written a simple reference-counting smart pointer class template called RefCountPtr<T>. It works in conjunction with another class, ReferenceCountable, which is responsible for the...
2
weaknessforcats
by: weaknessforcats | last post by:
Handle Classes Handle classes, also called Envelope or Cheshire Cat classes, are part of the Bridge design pattern. The objective of the Bridge pattern is to separate the abstraction from the...
41
by: Summercool | last post by:
Can we confirm the following? also someone said, Java also has "reference" like in C++, which is an "implicit pointer": Pointer and Reference --------------------- I am starting to see what...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
1
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.