简体   繁体   English

将引用参数传递给值参数

[英]passing reference argument to value argument

Disregarding any compiler optimizations likely to be done in the following C++ code below, is 忽略可能在以下C ++代码中完成的所有编译器优化是

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. 关键是,引用没有被取消引用,因为这不会发生-您只是复制正在引用的对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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