且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

C++ 引用、对象和指针之间的区别

更新时间:2023-02-12 14:55:40

他们都错了.

引用 本质上是另一个对象的同义词.在内部,它通常被实现为一个指针,但它的语法就像它所引用的对象一样.

指针是一个单独的对象,用于存储它指向的对象的内存地址(如果不指向对象,则为 0).

可以说引用是它所引用的对象(它肯定是这样操作的),但事实并非如此.如果引用超出范围,则它引用的对象不会被破坏,因此引用不是对象.

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.

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.