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 th开发者_开发百科e 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!
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.
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.
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 (Object& obj) {}
When you call f1
, for example f1(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
)
f2 (Object* obj) {}
When you call f2
,for example f1(&o1)
:
obj
is created and initialized with&o1
; that is similar like:
f2(){ Object* obj=&o1; // just for understanding what happens when you call f2(&o1) ...
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++?
精彩评论