How to pass a pointer variable as a reference parameter?

做~自己de王妃 提交于 2019-12-22 10:54:25

问题


When you have a function like this, the formal parameter is a reference, it becomes another name for the actual argument, so that when we modify the formal parameter inside the function, the original variable outside the function is changed.

void add_five(int& a)
{
    a += 5;
}

int main()
{
    int number = 3;
    add_five(number);
    std::cout << number << std::endl;  // prints 8

    return 0;
}

I have some code which works on a linked lists. And I am passing two Node*s into the function.

void LinkedList::move_five_nodes(Node* ptr1, Node* ptr2) { ... }

...

void LinkedList::anotherFunction()
{
    Node* leader;
    Node* trailer;
    ...
    move_five_nodes(leader, trailer);
    ...
}

I think that the rvalues memory addreses inside the leader and trailer pointer variables will be assigned into the Node* lvalues ptr1 and ptr2.

Node* ptr1 = leader;
Node* ptr2 = trailer;

The issue is that ptr1 and ptr2 are independent local variables inside the function. Initially, they point to the same place as the actual argument pointers. However, my function moves some nodes, and at the end of the function, the values of ptr1 and ptr2 are changed. I want these changes to also be in the original variables leader and trailer, just like references. So even when ptr1 and ptr2 expire, leader and trailer should go into their positions.

How would I do this? Maybe type cast the pointers into int&? Or maybe use pointers to pointers? I want to pass a pointer by reference, but I'm not sure how to do that.


回答1:


I want to pass a pointer by reference, but I'm not sure how to do that.

For this, consider the following snippet

#include <iostream>

void test(int*& t)
{
    t = nullptr;
}

int main()
{
    int* i = new int(4);

    test(i);

    if (i == nullptr)
        std::cout << "I was passed by reference" << std::endl;
}

in which is is passed by reference to test, where it is set to nullptr and the program prints: I was passed by reference.

I think this example should make clear how to pass a pointer by reference to a function.

So in your case the function signiture must change to

void LinkedList::move_five_nodes(Node*& ptr1, Node*& ptr2) { ... }


来源:https://stackoverflow.com/questions/52349745/how-to-pass-a-pointer-variable-as-a-reference-parameter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!