两个方法声明都是“按引用传递”吗?
用 C++ 编写函数的这两种方式有什么区别? 它们都是“通过引用传递”吗?通过“引用传递”,我的意思是该函数具有更改原始对象的能力(除非有另一个定义,但这是我的意图)。
根据我的理解,当您调用 f1 时,您会传入原始对象的“同义词”。当您调用 f2 时,您将传递一个指向该对象的指针。通过 f2 调用,是否会创建一个新的 Object*,而在 f1 调用中,什么也没有创建?
f1 (Object& obj) {}
f2 (Object* obj) {}
谢谢!
What is the difference between these two ways of writing a function in C++?
Are they both "pass by reference"? By "pass by reference", I mean that the function has the ability to alter the original object (unless there is another definition, but that is my intention).
From my understanding, when you call f1, you pass in a "synonym" of the original object. When you call f2, you are passing in a pointer to the object. With the f2 call, does a new Object* get created whereas in with f1 call, nothing does?
f1 (Object& obj) {}
f2 (Object* obj) {}
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
你的理解是正确的。
从技术上讲,f2 是按值传递的,该值是一个指针,但您可以使用该指针的副本来修改所指向的对象。
Your understanding is correct.
Technically, f2 is pass by value, with the value being a pointer, but you can use that copy of the pointer to modify the pointed-to object.
一般意义上,它们都是按引用传递的,但该短语通常不会用于描述指针版本,因为可能与 C++ 引用类型混淆。
They are both pass-by-reference in a general sense, but that phrase will not normally be used to describe the pointer version because of possible confusion with C++ reference types.
这两种用 C++ 编写函数的方法有什么区别?
f1 通过引用传递对象,f2 通过值传递指针。两者都可以通过引用直接修改对象 f1,通过取消引用指针修改对象 f2。
使用 f2 调用时,是否会创建一个新的 Object*,而使用 f1 调用时则不会创建任何内容?
f2 可以在该地址分配一个新对象,或者使用该地址已分配的对象,具体取决于。然而,按值传递指针不会调用 new,它只是指针的副本,该指针可能指向也可能不指向有效的分配对象。
查看 pst 作为评论发布的 wiki 链接。
What is the difference between these two ways of writing a function in C++?
f1 is passing an object by reference, f2 is passing a pointer by value. Both have the ability to modify the object f1 directly through the reference and f2 by dereferencing the pointer.
With the f2 call, does a new Object* get created whereas in with f1 call, nothing does?
f2 could allocate a new object at that address or use an already allocated object at that address depending. However passing a pointer by value will not call
new
it will simply be a copy of the pointer which may or may not point to a valid allocated object.Check out the wiki link posted as a comment by pst.
当您调用
f1
时,例如f1(o1)
:obj
成为o1
的另一个名称(别名),就是这样。所以o1
只是obj
的别名;它们具有相同的地址(您可以检查&obj==&o1
是否为true
)当您调用
f2
时,例如 < code>f1(&o1):obj
使用&o1
创建并初始化;这类似于:When you call
f1
, for examplef1(o1)
:obj
becomes the other name foro1
(alias), that's it. Soo1
is just alias forobj
; they have the same address (you can check that&obj==&o1
istrue
)When you call
f2
,for examplef1(&o1)
:obj
is created and initialized with&o1
; that is similar like:指针可以为空,而引用不能为空。
请参阅:
C++中的指针变量和引用变量?
A pointer can be null where a reference can not.
See:
What are the differences between a pointer variable and a reference variable in C++?