Optional function parameters: Use default arguments (NULL) or overload the function?

前端 未结 12 1539
情书的邮戳
情书的邮戳 2020-12-08 00:44

I have a function that processes a given vector, but may also create such a vector itself if it is not given.

I see two design choices for such a case, where a func

12条回答
  •  旧巷少年郎
    2020-12-08 01:12

    In C++ you should avoid allowing valid NULL parameters whenever possible. The reason is that it substantially reduces callsite documentation. I know this sounds extreme but I work with APIs that take upwards of 10-20 parameters, half of which can validly be NULL. The resulting code is almost unreadable

    SomeFunction(NULL, pName, NULL, pDestination);
    

    If you were to switch it to force const references the code is simply forced to be more readable.

    SomeFunction(
      Location::Hidden(),
      pName,
      SomeOtherValue::Empty(),
      pDestination);
    

提交回复
热议问题