c++ - 指针传递和引用传递

标签 c++ pointers reference parameter-passing

Possible Duplicate:
What are the differences between pointer variable and reference variable in C++?
Are there benefits of passing by pointer over passing by reference in C++?

在这两种情况下,我都取得了结果。 那么什么时候比另一个更受欢迎呢?我们使用其中一种的原因是什么?

#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\n";
    cout<<"a="<<a<<" b="<<b<<"\n";

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

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

输出

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&& <=> [no C equivalent] (C++11)

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

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

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

关于c++ - 指针传递和引用传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8571078/

相关文章:

c++ - 在 vector 练习中为体系结构x86_64编译C++不明符号

c++ - 返回模板化的依赖类型

c++ - Qt C++ : Multiple Q_NAMESPACE for the same namespace in different files

java - 添加 ImageIcon 的路径 - Java

c++ - CPPUNIT:我们真的每次测试都需要一个函数吗?

c - 如何测试下面的代码?如果我为声明为 'unsigned int' 的变量提供有符号整数,会发生什么?

C++ 函数指针数组错误

c - 在代码运行期间,初始化的指针是否可能为 NULL?

c++ - 将 Eigen 对象作为参数传递时的指针与引用差异

c# - 创建一个虚拟容器以便可以重新分配内部对象而不丢失? (C#)