use*_*361 4 c++ pointers reference pass-by-reference
我最近*&在函数中遇到了一个参数。
据我了解,它类似于**。
为什么在更改指针的函数中需要它?例如,带有new关键字
假设我有一个指针int* a,如果我想a = new int;在该函数中进行操作,为什么还要将参数作为“指针引用”传递?
如果函数int*以其参数为参数,则指针将通过值本身传递,这意味着函数内部对指针本身(不是指针对象)的任何修改都与原始指针无关。例如
void foo(int* a) { a = new int; }
int* a = nullptr;
foo(a);
// a is still nullptr here
Run Code Online (Sandbox Code Playgroud)
如果将参数类型更改为int*&它,则将有所不同。
void foo(int*& a) { a = new int; }
int* a = nullptr;
foo(a);
// a gets modified
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
125 次 |
| 最近记录: |