指向引用的指针和指向指针的引用之间的区别
C++ 中指向引用的指针、指向指针的引用和指向指针的指针有什么区别?
What is the difference between pointer to a reference, reference to a pointer and pointer to a pointer in C++?
哪一个应该比另一个更受欢迎?
Where should one be preferred over the other?
推荐答案
首先,对指针的引用就像对任何其他变量的引用:
First, a reference to a pointer is like a reference to any other variable:
void fun(int*& ref_to_ptr)
{
ref_to_ptr = 0; // set the "passed" pointer to 0
// if the pointer is not passed by ref,
// then only the copy(parameter) you received is set to 0,
// but the original pointer(outside the function) is not affected.
}
在 C++ 中指向引用的指针是非法的,因为 - 与指针不同 - 引用只是一个概念,它允许程序员为其他东西制作别名.指针是内存中的一个位置,它具有其他东西的地址,但引用不是.
A pointer to reference is illegal in C++, because -unlike a pointer- a reference is just a concept that allows the programmer to make aliases of something else. A pointer is a place in memory that has the address of something else, but a reference is NOT.
如果您坚持将引用作为指针处理,那么最后一点可能不是很清楚.例如:
Now the last point might not be crystal clear, if you insist on dealing with references as pointers. e.g.:
int x;
int& rx = x; // from now on, rx is just like x.
// Unlike pointers, refs are not real objects in memory.
int* p = &x; // Ok
int* pr = ℞ // OK! but remember that rx is just x!
// i.e. rx is not something that exists alone, it has to refer to something else.
if( p == pr ) // true!
{ ... }
从上面的代码可以看出,当我们使用引用时,我们并不是在处理与其所引用的东西分开的东西.所以,引用的地址就是它所引用的地址.这就是为什么就您所谈论的内容而言,没有称为参考地址这样的东西.
As you can see from the above code, when we use the reference, we are not dealing with something separated from what it refers to. So, the address of a reference is just the address of what it refers to. Thats why there is no such thing called the address of the reference in terms of what you are talking about.
相关文章