Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/164.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 什么是对指针的引用?_C++_Parameter Passing - Fatal编程技术网

C++ 什么是对指针的引用?

C++ 什么是对指针的引用?,c++,parameter-passing,C++,Parameter Passing,我最近看到一个函数被声明为: void func(type* &param); 我已经知道type*param和type¶m之间的区别。以上与它们有什么不同?什么时候用这个?建议这样做吗?上述功能不仅可以修改指向的对象,还可以修改指针本身。作为一个例子,考虑下面的代码: void func(int*& ptr) { *ptr = 1; ptr = 0; } int main() { int x = 0; int* y = &x;

我最近看到一个函数被声明为:

void func(type* &param);

我已经知道
type*param
type¶m
之间的区别。以上与它们有什么不同?什么时候用这个?建议这样做吗?

上述功能不仅可以修改指向的对象,还可以修改指针本身。作为一个例子,考虑下面的代码:

void func(int*& ptr) {
    *ptr = 1;
    ptr = 0;
}

int main() {
    int x = 0;
    int* y = &x;
    func(y);
}
在执行结束时,
x
具有值
1
y
0
(如您所示)


注意,在本例中,我使用了
0
作为空指针,但是如果您使用的是C++11,那么您(它没有重载的
operaor),让我们比较所有三个选项:

  • void func(type*param);//“param”是一个“type*”变量
  • void func(type¶m);//“param”是对“type”变量的引用
  • void func(type*¶m);//“param”是对“type*”变量的引用

当然,如果您执行
*param=…
,则将影响
param
指向的内存内容。例如,您也可以执行
param[5]=…
,并影响该内存空间中的其他区域


在这里,您只需更改引用变量本身,因此比将函数声明为
void func(type*param)
更安全,然后通过调用
func(¶m)
传递
type param
的地址


这类似于将函数声明为
void func(type**param)
,然后通过调用
func(¶m)
传递
type*param
的地址,但同样,出于上述相同原因,这更安全



它与
type¶m
相同,这里的类型是
type*
template<class Type> using ptr = Type*;
ptr<int>& x;
std::unique_ptr<int>& x;
void func(const int*const& ptr)
free_my_int(int*& ptr) {
    delete ptr;
    ptr = nullptr;
}

int* x = new int(42);
free_my_int(x);
void func(type* param)
{
    type x;
    ...
    param = &x;
    // Argument 'param' is regarded as a local variable in this function,
    // so setting 'param = ...' will have no effect outside this function
}
void func(type& param)
{
    type x;
    ...
    param = x;
    // Argument 'param' is regarded as a reference to a variable outside this
    // function, so setting 'param = ...' will effect the referenced variable
}
void func(type*& param)
{
    type x;
    ...
    param = &x;
    // Argument 'param' is regarded as a reference to a variable outside this
    // function, so setting 'param = ...' will effect the referenced variable
}