指针变量和引用变量之间的区别是什么?
当前回答
我对引用和指针有一个类比,将引用看作对象的另一个名称,将指针看作对象的地址。
// receives an alias of an int, an address of an int and an int value
public void my_function(int& a,int* b,int c){
int d = 1; // declares an integer named d
int &e = d; // declares that e is an alias of d
// using either d or e will yield the same result as d and e name the same object
int *f = e; // invalid, you are trying to place an object in an address
// imagine writting your name in an address field
int *g = f; // writes an address to an address
g = &d; // &d means get me the address of the object named d you could also
// use &e as it is an alias of d and write it on g, which is an address so it's ok
}
其他回答
除了语法糖,引用是常量指针(而不是指向常量的指针)。在声明引用变量时,必须确定它所指的内容,以后不能更改它。
更新:现在我再考虑一下,有一个重要的区别。
常量指针的目标可以通过获取其地址并使用常量转换来替换。
引用的目标不能以UB以外的任何方式替换。
这应该允许编译器对引用进行更多优化。
指针和引用之间有一个根本的区别,我没有看到任何人提到过:引用支持函数参数中的引用传递语义。指针,虽然它最初不可见,但它不可见:它们只提供值传递语义。这在本文中得到了很好的描述。
当做&rzej公司
将指针视为名片:
它让你有机会联系某人它可以是empy它可能包含错误或过时的信息你不确定上面提到的某人还活着你不能直接与卡片通话,你只能用它打电话给某人也许有很多这样的卡片
将推荐人视为与某人的主动通话:
你很确定你联系过的人还活着您可以直接通话,无需额外通话你很确定你不会和一个空地方或一块垃圾说话你不能确定你是唯一一个当前正在与此对象交谈的人
引用的另一个有趣用法是提供用户定义类型的默认参数:
class UDT
{
public:
UDT() : val_d(33) {};
UDT(int val) : val_d(val) {};
virtual ~UDT() {};
private:
int val_d;
};
class UDT_Derived : public UDT
{
public:
UDT_Derived() : UDT() {};
virtual ~UDT_Derived() {};
};
class Behavior
{
public:
Behavior(
const UDT &udt = UDT()
) {};
};
int main()
{
Behavior b; // take default
UDT u(88);
Behavior c(u);
UDT_Derived ud;
Behavior d(ud);
return 1;
}
默认风格使用引用的“bind const reference to a temporary”方面。
你忘记了最重要的部分:
带指针的成员访问使用->使用引用的成员访问。
foo.bar明显优于foo->bar,就像vi明显优于Emacs一样:-)