Google's style guide about input/output parameters as pointers

前端 未结 4 2290
终归单人心
终归单人心 2021-02-19 10:41

The Google C++ Style Guide draws a clear distinction (strictly followed by cpplint.py) between input parameters(→ const ref, value) and input-output or output parameters (→ non

4条回答
  •  伪装坚强ぢ
    2021-02-19 11:40

    You're first question: "So, what's the point to always demand a pointer if I want to avoid the pointer to be null?"

    Using a pointer announces to the caller that their variable may be modified. If I am calling foo(bar), is bar going to be modified? If I am calling foo(&bar) it's clear that the value of bar may be modified.
    There are many examples of functions which take in a null indicating an optional output parameter (off the top of my head time is a good example.)

    Your second question: "Why only use references for input arguments?"

    Working with a reference parameter is easier than working with a pointer argument.

    int foo(const int* input){
        int return = *input;
    
        while(*input < 100){
            return *= *input;
            (*input)++;
        }
    }
    

    This code rewritten with a reference looks like:

    int foo(const int& input){
        int return = input;
    
        while(input < 100){
            return *= input;
            input++;
        }
    }
    

    You can see that using a const int& input simplifies the code.

提交回复
热议问题