Is there a way to make passing by reference, and passing by value explicit in the function call?

前端 未结 7 1511
北荒
北荒 2021-02-18 13:43

If you were to look at this code,

int x = 0;
function(x);
std::cout << x << \'\\n\';

you would not be able to verify through any me

7条回答
  •  [愿得一人]
    2021-02-18 14:03

    Some people insist that the correct way to pass mutable object is to use a pointer. That is, you would pass

    Lowercase(&str);
    

    ... and Lowercase() would, obviously, be implemented to take a pointer. That approach may suit your needs.

    I want to mention, however, that this is not what I would do! Instead, the approach I favor is to use appropriate names instead. For example,

    inplace_lowercase(str);
    

    pretty much says what it is going to do. Clearly, inplace_lowercase() would actually be an algorithm and with a bit of magic could be reasonably be called as

    inplace_lowercase(str.begin() + 1, str.end());
    

    as well.

    Here are a few reasons why I don't like passing arguments by pointer and/or why I don't believe in an explicit indication of how the argument is passed:

    • Pointers can be null. A mandated reference parameters should, in my opinion, be a reference.
    • Passing by pointer still doesn't indicate whether the argument may be modified are not as the argument may be a T const*.
    • Having meaningful names makes it actually easier to understand what's going on in the first place.
    • Calling something without consulting its documentation and/or knowing what the called function will do doesn't work anyway and indicating how things are passed is trying to cure symptoms of a deeper problem.

提交回复
热议问题