c++ - 在 C++ 中通过引用/值传递

标签 c++ pass-by-reference pass-by-value

我想澄清按值和按引用之间的区别。

我画了一幅画

enter image description here

因此,对于按值传递,

使用不同的引用创建相同对象的拷贝,并为局部变量分配新引用,因此指向新拷贝

如何理解单词:
"
如果函数修改了该值,修改也会出现
在值传递和引用传递的调用函数范围内
"

谢谢!

最佳答案

我认为不传达引用传递的含义会产生很多困惑。当有些人说通过引用传递时,他们通常不是指参数本身,而是被引用的对象。其他人说通过引用传递意味着对象不能在被调用者中更改。例子:

struct Object {
    int i;
};

void sample(Object* o) { // 1
    o->i++;
}

void sample(Object const& o) { // 2
    // nothing useful here :)
}

void sample(Object & o) { // 3
    o.i++;
}

void sample1(Object o) { // 4
    o.i++;
}

int main() {
    Object obj = { 10 };
    Object const obj_c = { 10 };

    sample(&obj); // calls 1
    sample(obj) // calls 3
    sample(obj_c); // calls 2
    sample1(obj); // calls 4
}

有些人会声称 1 和 3 是通过引用传递,而 2 是通过值传递。另一组人说除了最后一个之外都是按引用传递,因为对象本身没有被复制。

我想在这里定义我声称通过引用传递的内容。可以在此处找到对其的一般概述:Difference between pass by reference and pass by value .第一个和最后一个是值传递,中间两个是引用传递:
    sample(&obj);
       // yields a `Object*`. Passes a *pointer* to the object by value. 
       // The caller can change the pointer (the parameter), but that 
       // won't change the temporary pointer created on the call side (the argument). 

    sample(obj)
       // passes the object by *reference*. It denotes the object itself. The callee
       // has got a reference parameter.

    sample(obj_c);
       // also passes *by reference*. the reference parameter references the
       // same object like the argument expression. 

    sample1(obj);
       // pass by value. The parameter object denotes a different object than the 
       // one passed in.

我投票支持以下定义:

An argument (1.3.1) is passed by reference if and only if the corresponding parameter of the function that's called has reference type and the reference parameter binds directly to the argument expression (8.5.3/4). In all other cases, we have to do with pass by value.



这意味着以下内容是按值传递的:
void f1(Object const& o);
f1(Object()); // 1

void f2(int const& i);
f2(42); // 2

void f3(Object o);
f3(Object());     // 3
Object o1; f3(o1); // 4

void f4(Object *o);
Object o1; f4(&o1); // 5
1是按值传递,因为它没有直接绑定(bind)。实现可以复制临时文件,然后将该临时文件绑定(bind)到引用。 2是按值传递的,因为实现会初始化文字的临时值,然后绑定(bind)到引用。 3是传值,因为参数没有引用类型。 4出于同样的原因,是按值传递。 5是按值传递,因为参数没有引用类型。以下情况通过引用传递(根据 8.5.3/4 和其他规则):
void f1(Object *& op);
Object a; Object *op1 = &a; f1(op1); // 1

void f2(Object const& op);
Object b; f2(b); // 2

struct A { };
struct B { operator A&() { static A a; return a; } };
void f3(A &);
B b; f3(b); // passes the static a by reference

关于c++ - 在 C++ 中通过引用/值传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61115235/

相关文章:

c++ - RapidXML 从文件中读取 - 这里有什么问题?

c++ - WOW64 程序如何覆盖其命令行参数,如 WMI 所示?

c++ - 在 C 中通过 const 引用传递

Java数组:Java pass by reference and pass by value?

c++ - 将整数参数转发给一个构造函数,将 float 转发给另一个构造函数

c++ - 将类声明放在 .cpp 文件中

python - 推荐人、被推荐人、 parent 和 child

perl - 如何通过 Perl 引用传递哈希表

Python 变量的地址分配

java 按值传递原语与对象