简体   繁体   中英

C++ passing in pointer to a function with reference parameters

I understand calling foo(value) fine, but how does calling foo(*p) produce the same results? I thought it would error, but it works just fine.

*p is dereferencing the pointer, getting the value at address stored in p, so isn't it equivalent to calling foo(5)?

void foo(int &ptr)
{
    ptr = 6;
}

int main()
{
    using namespace std;
    int value = 5;
    int *p = &value;
    cout << "value = " << value << '\n';
    foo(*p);
    cout << "value = " << value << '\n';
    return 0;
}

* operator used for dereferencing pointer returns lvalue just like identifier that stands for variable such as value , which is a primary expression. So both of them will be accepted for reference arguments.

Quote from N3337 5.1.1 General (5.1 Primary expressions):

8 An identifier is an id-expression provided it has been suitably declared (Clause 7). [...] The type of the expression is the type of the identifier. The result is the entity denoted by the identifier. The result is an lvalue if the entity is a function, variable, or data member and a prvalue otherwise.

Quote from N3337 5.3.1 Unary operators:

1 The unary * operator performs indirection: the expression to which it is applied shall be a pointer to an object type, or a pointer to a function type and the result is an lvalue referring to the object or function to which the expression points. If the type of the expression is “pointer to T,” the type of the result is “T.”

First, when you dereference your pointer p, you get an integer value (because you declare it as a pointer to an integer). In this case, dereferencing p gets you the, er, value of your 'value' variable. With me so far?

So now, what happens in the function call? The program dereferences the pointer p, and then passes an lvalue reference to your variable (value) to the function. The function is defined to take a reference (a pointer with some syntactic sugar). So yes, you are correct in thinking it is dereferenced to an integer. However, C++ passes the address of the value variable anyway, rather than an integer variable, because you've told it to only accept references in the function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM