通过指针&通过引用传递

2021-12-13 00:00:00 reference parameter-passing pointers c++

可能的重复:
指针变量和指针变量有什么区别C++中的引用变量?
路过有好处吗在 C++ 中通过引用传递指针?

在这两种情况下,我都达到了结果.那么什么时候一个比另一个更受欢迎呢?我们使用一个而不是另一个的原因是什么?

In both cases, I achieved the result. So when is one preferred over the other? What are the reasons we use one over the other?

#include <iostream>
using namespace std;
void swap(int* x, int* y)
{
    int z = *x;
    *x=*y;
    *y=z;
}
void swap(int& x, int& y)
{
    int z = x;
    x=y;
    y=z;
}

int main()
{
    int a = 45;
    int b = 35;
    cout<<"Before Swap
";
    cout<<"a="<<a<<" b="<<b<<"
";

    swap(&a,&b);
    cout<<"After Swap with pass by pointer
";
    cout<<"a="<<a<<" b="<<b<<"
";

    swap(a,b);
    cout<<"After Swap with pass by reference
";
    cout<<"a="<<a<<" b="<<b<<"
";
}

输出

Before Swap
a=45 b=35
After Swap with pass by pointer
a=35 b=45

After Swap with pass by reference
a=45 b=35

推荐答案

引用在语义上如下:

T&<=>*(T * const)

const T&<=>*(T const * const)

T&&<=>[无 C 等价物] (C++11)

与其他答案一样,C++ 常见问题解答中的以下内容是单行答案:可能时引用,需要时使用指针.

As with other answers, the following from the C++ FAQ is the one-line answer: references when possible, pointers when needed.

优于指针的一个优点是您需要显式转换才能传递 NULL.不过还是有可能的.在我测试过的编译器中,没有一个会发出以下警告:

An advantage over pointers is that you need explicit casting in order to pass NULL. It's still possible, though. Of the compilers I've tested, none emit a warning for the following:

int* p() {
    return 0;
}
void x(int& y) {
  y = 1;
}
int main() {
   x(*p());
}

相关文章