Passing a modifiable parameter to c++ function

前端 未结 12 1616
余生分开走
余生分开走 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:38

    Advantages to passing by reference:

    • Forces user to supply a value.
    • Less error-prone: Handles pointer dereferencing itself. Don't have to check for null inside.
    • Makes the calling code look much cleaner.

    Advantages to passing pointer by value:

    • Allows null to be passed for "optional" parameters. Kinda an ugly hack, but sometimes useful.
    • Forces caller to know what is being done w/ the parameter.
    • Gives the reader half a clue of what might be being done w/ the parameter without having to read the API.

    Since reference passing is in the language, any non-pointer parameters might be getting modified too, and you don't know that pointer values are being changed. I've seen APIs where they are treated as constants. So pointer passing doesn't really give readers any info that they can count on. For some people that might be good enough, but for me it isn't.

    Really, pointer passing is just an error-prone messy hack leftover from C which had no other way to pass values by reference. C++ has a way, so the hack is no longer needed.

提交回复
热议问题