Pointer vs. Reference

后端 未结 12 1429
闹比i
闹比i 2020-11-22 11:13

What would be better practice when giving a function the original variable to work with:

unsigned long x = 4;

void func1(unsigned long& val) {
     val          


        
12条回答
  •  悲哀的现实
    2020-11-22 11:37

    I really think you will benefit from establishing the following function calling coding guidelines:

    1. As in all other places, always be const-correct.

      • Note: This means, among other things, that only out-values (see item 3) and values passed by value (see item 4) can lack the const specifier.
    2. Only pass a value by pointer if the value 0/NULL is a valid input in the current context.

      • Rationale 1: As a caller, you see that whatever you pass in must be in a usable state.

      • Rationale 2: As called, you know that whatever comes in is in a usable state. Hence, no NULL-check or error handling needs to be done for that value.

      • Rationale 3: Rationales 1 and 2 will be compiler enforced. Always catch errors at compile time if you can.

    3. If a function argument is an out-value, then pass it by reference.

      • Rationale: We don't want to break item 2...
    4. Choose "pass by value" over "pass by const reference" only if the value is a POD (Plain old Datastructure) or small enough (memory-wise) or in other ways cheap enough (time-wise) to copy.

      • Rationale: Avoid unnecessary copies.
      • Note: small enough and cheap enough are not absolute measurables.

提交回复
热议问题