Are there benefits of passing by pointer over passing by reference in C++?
What are the benefits of passing by pointer over passing by reference in C++?
Lately, I have seen a number of examples that chose passing function arguments by pointers instead of passing by reference. Are there benefits to doing this?
Example:
func(SPRITE *x);
with a call of
func(&mySprite);
vs.
func(SPRITE &x);
with a call of
func(mySprite);
A pointer can receive a NULL parameter, a reference parameter can not. If there's ever a chance that you could want to pass "no object", then use a pointer instead of a reference.
Also, passing by pointer allows you to explicitly see at the call site whether the object is passed by value or by reference:
// Is mySprite passed by value or by reference? You can't tell
// without looking at the definition of func()
func(mySprite);
// func2 passes "by pointer" - no need to look up function definition
func2(&mySprite);
Passing by pointer
nothing
. This can be used to provide optional arguments. Pass by reference
string s = &str1 + &str2;
using pointers. void f(const T& t); ... f(T(a, b, c));
void f(const T& t); ... f(T(a, b, c));
, pointers cannot be used like that since you cannot take the address of a temporary. Allen Holub's "Enough Rope to Shoot Yourself in the Foot" lists the following 2 rules:
120. Reference arguments should always be `const`
121. Never use references as outputs, use pointers
He lists several reasons why references were added to C++:
const
references allow you to have pass-by-value semantics while avoiding a copy His main point is that references should not be used as 'output' parameters because at the call site there's no indication of whether the parameter is a reference or a value parameter. So his rule is to only use const
references as arguments.
Personally, I think this is a good rule of thumb as it makes it more clear when a parameter is an output parameter or not. However, while I personally agree with this in general, I do allow myself to be swayed by the opinions of others on my team if they argue for output parameters as references (some developers like them immensely).
链接地址: http://www.djcxy.com/p/460.html上一篇: 如何通过引用传递变量?