简体   繁体   中英

passing reference argument to value argument

Disregarding any compiler optimizations likely to be done in the following C++ code below, is

void f(int n) {
    n += 1;
}

void g(int &n) {
    f(n);
}

equivalent to

void f(int n) {
    n += 1;
}

void g(int *n) {
    f(*n);
}

?

So still value copies can be made in places not so explicitly visible when using reference arguments?

EDIT I am asking about whether actual value copies can be made with reference arguments. When using pointers as in the second case, I explicitly dereference the pointer to pass by value, but will using reference arguments sometimes do the dereferencing implicitly? is my question.

I am asking about whether actual value copies can be made with reference arguments.

Absolutely. The fact that it's a reference is irrelevant. You can treat it just like the object it references.

When using pointers as in the second case, I explicitly dereference the pointer to pass by value, but will using reference arguments sometimes do the dereferencing implicitly?

You're thinking of references as some kind of hidden pointer. The terminology doesn't really help here. "Dereferencing" is something you do to pointers, not to references. In fact, the standard has changed to use "perform indirection" instead of "dereference" to help clarify this. The point is, the reference isn't being dereferenced, because that's not something that happens - you are just copying the object that is being referenced.

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