Passing a modifiable parameter to c++ function

前端 未结 12 1639
余生分开走
余生分开走 2020-12-06 19:12

Provided, I want to pass a modifiable parameter to a function, what should I choose: to pass it by pointer or to pass it by reference?

  1. bool GetFoo ( Foo& w
12条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-06 19:40

    The benefit to a pointer is that you can pass nothing, ie. use it as if the parameter was completely optional and not have a variable the caller passes in.

    References otherwise are safer, if you have one its guaranteed to exist and be writeable (unless const of course)

    I think its a matter of preference otherwise, but I don't like mixing the two as I think it makes maintainace and readability of your code harder to do (especially as your 2 functions look the same to the caller)

提交回复
热议问题