指向引用的指针和指针的引用之间的差异 [英] Difference between pointer to a reference and reference to a pointer

查看:163
本文介绍了指向引用的指针和指针的引用之间的差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

指向引用的指针,指向指针的指针和指向C ++中的指针的指针之间有什么区别?

What is the difference between pointer to a reference, reference to a pointer and pointer to a pointer in C++?

在哪里应该优先于另一个? / p>

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!
{ ... }



从上面的代码可以看出,引用,我们不处理与它所指的东西分开的东西。因此,引用的地址只是它所引用的地址。这就是为什么没有这样的东西称为地址的参考根据你在说什么。

这篇关于指向引用的指针和指针的引用之间的差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆