可以将对指针的引用作为函数参数传递吗?

Is it OK to pass reference to a pointer as a function argument?

我的理解是,在 C++ 中 & 和 * 相互抵消,即 int *&p 本质上等于 p 作为它在整数 p 地址处的值。

鉴于上述情况,现在传递对指针的引用是否有效,也就是说我正在尝试将对指针的引用作为函数中的参数传递,如下所示?

void func(int* &p)

上面的结果不会导致用 & 取消 * 而只是 int p 吗? 如果我尝试以类似的方式传递对 class 对象指针的引用,它有多正确?

#include <iostream>

using namespace std;

int gobal_var = 42;

// function to change Reference to pointer value
void changeReferenceValue(int*& pp)
{
    pp = &gobal_var;
}

int main()
{
    int var = 23;
    int* ptr_to_var = &var;

    cout << "Passing a Reference to a pointer to function" << endl;

    cout << "Before :" << *ptr_to_var << endl; // display 23

    changeReferenceValue(ptr_to_var);

    cout << "After :" << *ptr_to_var << endl; // display 42

    return 0;
}

您是正确的,& 地址运算符和 * 间接运算符在 expression.

中使用时相互抵消

但是,当在 declaration 中使用时,这些运算符具有非常不同的含义。在声明中,* 表示“指针”,& 表示“引用”。因此,当在声明中使用时,它们不会相互抵消。

int*& 类型的对象只是对指向 int.

的指针的引用