Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
982 views
in Technique[技术] by (71.8m points)

oop - C++ difference between reference, objects and pointers

This is a question from an exam in an advanced course in OOP, taught in C++ (in TAU university, this semester):

Q: What is the difference between a C++ pointer and a reference?

A.  A reference is the entire object while a pointer is only the address of it.
B.  The same meaning, and difference is only in syntax and usage.
C.  The syntax used to access the object.
D.  Pointers are simple address to the object while a reference uses the virtual table.

Which is the correct answer?

The course teacher claims that A is the correct one, and that a reference to an object is, in fact, the object itself. Is that correct? I realize that accessing the reference is equivalent to accessing the object itself, however, when destructing a reference, we do not destruct the object itself. A reference is an alternative name for the object, but saying that reference==object true?

BTW, the lecturer gave the following link to an faq as support for his claim, a quote:

"Important note: Even though a reference is often implemented using an address in the underlying assembly language, please do not think of a reference as a funny looking pointer to an object. A reference is the object. It is not a pointer to the object, nor a copy of the object. It is the object."

But still, I believe this is incorrect.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

They're all wrong.

A reference is essentially a synonym for another object. Internally, it is often implemented as a pointer, but it has the syntax as if it were the object it refers to.

A pointer is a separate object that stores the memory address of the object it points to (or 0 if it doesn't point to an object).

You could say that the reference is the object that it refers to (it certainly acts that way), but it is not. If a reference goes out of scope then the object it refers to is not destructed, so the reference is not the object.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...