【问题标题】:the purpose of function parameters with two indirection operators (C++)具有两个间接运算符 (C++) 的函数参数的用途
【发布时间】:2020-02-08 08:02:48
【问题描述】:

具有两个间接运算符的函数参数的用途是什么?

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


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;
}

【问题讨论】:

  • 它改变了你的价值1。使用 cout
  • 您永远无法更改任何地址。一旦某个东西被创造出来,它就会一直停留在同一个地方,直到它不再存在为止。

标签: c++ function parameters


【解决方案1】:

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

例如StringFromIID

HRESULT StringFromIID(
  REFIID   rclsid,
  LPOLESTR *lplpsz
);

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

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

【讨论】:

    【解决方案2】:

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

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

    我相信您预计 ++**foo 会将 value1 移动到下一个位置,但事实并非如此。

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

    【讨论】:

      【解决方案3】:

      pint ** 类型时,

      ++**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++ 中很常见,因为人们喜欢在各处少输入 *

      【讨论】:

        猜你喜欢
        • 2010-12-28
        • 2019-05-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-11-14
        • 2012-04-23
        • 2013-06-13
        相关资源
        最近更新 更多