指针变量和引用变量之间的区别是什么?


当前回答

如果遵循传递给函数的参数的约定,则可以使用引用和指针之间的差异。Const引用用于传递到函数中的数据,指针用于传递出函数的数据。在其他语言中,您可以使用诸如In和out之类的关键字来明确表示这一点。在C++中,您可以(按照约定)声明等价的。例如

void DoSomething(const Foo& thisIsAnInput, Foo* thisIsAnOutput)
{
   if (thisIsAnOuput)
      *thisIsAnOutput = thisIsAnInput;
}

使用引用作为输入和指针作为输出是Google风格指南的一部分。

其他回答

引用的另一个有趣用法是提供用户定义类型的默认参数:

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”方面。

指针和引用之间的差异

指针可以初始化为0,而引用不能初始化。事实上,引用也必须引用对象,但指针可以是空指针:

int* p = 0;

但我们不能有int&p=0;以及int&p=5;。

事实上,要正确执行此操作,我们必须首先声明并定义了一个对象,然后才能引用该对象,因此前面代码的正确实现将是:

Int x = 0;
Int y = 5;
Int& p = x;
Int& p1 = y;

另一个重要的点是,我们可以在不初始化的情况下声明指针,但是在引用的情况下,不能这样做,因为引用必须始终引用变量或对象。然而,这样使用指针是有风险的,因此通常我们检查指针是否确实指向某个对象。在引用的情况下,不需要这样的检查,因为我们已经知道在声明期间引用对象是强制性的。

另一个区别是指针可以指向另一个对象,但是引用总是引用同一个对象

Int a = 6, b = 5;
Int& rf = a;

Cout << rf << endl; // The result we will get is 6, because rf is referencing to the value of a.

rf = b;
cout << a << endl; // The result will be 5 because the value of b now will be stored into the address of a so the former value of a will be erased

另一点:当我们有一个类似STL模板的模板时,此类类模板将始终返回一个引用,而不是指针,以便使用运算符[]轻松读取或分配新值:

Std ::vector<int>v(10); // Initialize a vector with 10 elements
V[5] = 5; // Writing the value 5 into the 6 element of our vector, so if the returned type of operator [] was a pointer and not a reference we should write this *v[5]=5, by making a reference we overwrite the element by using the assignment "="

引用是另一个变量的别名,而指针保存变量的内存地址。引用通常用作函数参数,因此传递的对象不是副本而是对象本身。

    void fun(int &a, int &b); // A common usage of references.
    int a = 0;
    int &b = a; // b is an alias for a. Not so common to use. 

不能像指针一样取消引用,当取消引用时,

引用和指针都是通过地址工作的。。。

so

你可以这样做

int*val=0xDEADBEEF;*val是0xDEADBEEF的值。

你不能这样做int&V=1;

*不允许使用val。

除了语法糖,引用是常量指针(而不是指向常量的指针)。在声明引用变量时,必须确定它所指的内容,以后不能更改它。

更新:现在我再考虑一下,有一个重要的区别。

常量指针的目标可以通过获取其地址并使用常量转换来替换。

引用的目标不能以UB以外的任何方式替换。

这应该允许编译器对引用进行更多优化。