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

  • Caller has to take the address -> not transparent
  • A 0 value can be provided to mean nothing . This can be used to provide optional arguments.
  • Pass by reference

  • Caller just passes the object -> transparent. Has to be used for operator overloading, since overloading for pointer types is not possible (pointers are builtin types). So you can't do string s = &str1 + &str2; using pointers.
  • No 0 values possible -> Called function doesn't have to check for them
  • Reference to const also accepts temporaries: 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.
  • Last but not least, references are easier to use -> less chance for bugs.

  • 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++:

  • they are necessary to define copy constructors
  • they are necessary for operator overloads
  • 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

    上一篇: 如何通过引用传递变量?

    下一篇: 在C ++中通过引用传递指针会带来什么好处?