c reference semantic isn't explicit in caller's code

前端 未结 1 791
暗喜
暗喜 2021-01-27 09:05

Can anybody explain this?

Old line C programmers sometimes don\'t like references since they provide reference semantics that isn\'t explicit in the calle

相关标签:
1条回答
  • 2021-01-27 09:53

    When you use a C++ function like:

    void make42 (int &x) { x = 42; }
    

    and call it thus:

    int y = 7;
    make42 (y); // y is now 42
    

    then there is no indication in the make42 (y) call that y can be changed. Exactly the same function call would be made if it wasn't a pass-by-reference parameter:

    void trymake42 (int x) { x = 42; }
    
    int y = 7;
    trymake42 (y); // y is still 7
    

    In C code, it would be something like:

    void make42 (int *px) {
        *px = 42;
    }
    int y = 7;
    make42 (&y);
    

    making it clear that a change to y is a real possibility when calling the function.

    So what these "old line" C coders would be concerned about is a line like:

    someFunction (x);
    

    where they would have no idea from just that whether x would change or not.

    I have to say that, as one of these old line coders, it's far less of a problem than the quote seems to imply. Without seeing the prototype, I can't even tell what the parameter types should be, or how many there are, or their order.

    So, having to refer to said prototype to figure out if a parameter is pass-by-value or pass-by-reference is not really an big deal.

    C# takes a different tack with the out and ref parameter modifiers but that still makes it explicit in the call whether the variable is pass-by-value or pass-by-reference.

    0 讨论(0)
提交回复
热议问题