具有两个间接寻址运算符 (C++) 的函数参数的用途

the purpose of function parameters with two indirection operators (C++)

本文关键字:函数 C++ 参数 间接寻址 两个 运算符      更新时间:2023-10-16

具有两个间接寻址运算符的函数参数的目的是什么?

由于引用调用正在更改原始变量的值,我认为具有两个间接寻址运算符的函数参数可能会更改原始值的地址。
但正如我下面的尝试所显示的那样,它没有:


void addrchanger(int**);
int main()
{
int value1 = 4;
int* value1ptr = &value1;
std::cout<<&value1<<std::endl;
addrchanger(&value1ptr);
std::cout<<&value1<<std::endl;
//the address of value1 doesn't change.
}
void addrchanger(int** foo)
{
//this is an attempt to change the address of value1 to the next slot
++**foo;
}

目的是传递指向指针的指针或指向数组的指针。对于 main((char** argv等历史函数,这种做法类似于 C(这就是为什么您还需要一个 argc,因为指针无法推断大小(。当您希望返回指针时,也会使用它,因此将指针传递给指针,就像在许多 Win32 函数中一样。

例如在 StringFromIID 中

HRESULT StringFromIID(
REFIID   rclsid,
LPOLESTR *lplpsz
);

您将传递一个双指针作为第二个参数(wchar_t**(,以便返回一个指针,它们必须像文档所说的那样被释放。

现在在C++中完全避免这种情况,并在任何必要的深度使用 std::vector。

void addrchanger(int** foo)函数可以更改:

  • 值:(**foo)++使int value1比5
  • 和地址:(*foo)++value1ptr指向value1后的下一个空格

我相信你期望++**foovalue1移动到下一个位置,但事实并非如此。

指针到指针对于矩阵声明也很有用,但大多数库,如GNU科学库,BLAS,OpenGLglLoadMatrixf(),更喜欢使用单个指针。

p的类型为int **时,

++**p

增加由**p表示的 int 的值。

为了更改指向的 int 的地址,您将使用

++*p

通过直接访问变量,您将对所有内容少使用一个*

int *p;
++*p; // increment the int value
++p; // increment the pointer

但是在这样的函数内部,每个参数都只是一个副本,所以如果你想在外面改变一些东西,你需要一个指向它的指针,这意味着所有内容都使用了一个*

function f(int **p) {
++**p; // increment the int value
++*p; // increment the pointer
// you can also increment the argument
// but you can't know whether it will then
// still point to another int pointer:
++p
}

此外,您可以在C++中使用 & 代替 *,后者仅用于将变量声明为引用,然后像秘密的隐藏指针一样工作。您再次少使用一个*,就像开始时在函数外部一样。

function f(int *&p) {
++*p; // increment the int value
++p; // increment the pointer
// you can also not increment the reference itself,
// as it is a hidden pointer.
}

这听起来很危险,因为谁会想要秘密指针?但这在C++很常见,因为人们喜欢到处打字*少。