Passing a modifiable parameter to c++ function

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

    I'd recommend that you consider (may not be best for every situation) returning Foo from the function rather than modifying a parameter. Your function prototype would look like this:

    Foo GetFoo() // const (if a member function)
    

    As you appear to be returning a success/failure flag, using an exception might be a better strategy.

    Advantages:

    • You avoid all of the pointer/reference issues
    • Simplifies life for the caller. Can pass the return value to other functions without using a local variable, for example.
    • Caller cannot ignore error status if you throw an exception.
    • Return value optimization means that it may be as efficient as modifying a parameter.

提交回复
热议问题