Is C++ Array passed by reference or by pointer?

前端 未结 3 608
臣服心动
臣服心动 2021-01-05 17:09

In school, our lecturer taught us that the entire array was passed by reference when we pass it to a function,.

However, recently I read a book. It

3条回答
  •  再見小時候
    2021-01-05 17:50

    Pass-by-pointer is a bit of a misnomer. It doesn't happen in C++. There is only pass-by-value and pass-by-reference. Pointers in particular are passed by value.

    The answer to your question is: it depends.

    Consider the following signatures:

    void foo(int *arr);
    void bar(int *&arr);
    void baz(int * const &arr);
    void quux(int (&arr)[42]);
    

    Assuming you are passing an array to each of these functions:

    • In foo(arr), your array is decayed to a pointer, which is then passed by value.
    • In bar(arr), this is a compiler error, because your array would decay to a (temporary) pointer, and this would be passed by reference. This is nearly always a bug, since the reason you would want a mutable reference is to change the value of the referent, and that would not be what would happen (you would change the value of the temporary instead). I add this since this actually does work on some compilers (MSVC++) with a particular extension enabled. If you instead decay the pointer manually, then you can pass that instead (e.g. int *p = arr; bar(p);)
    • In baz(arr), your array decays to a temporary pointer, which is passed by (const) reference.
    • In quux(arr), your array is passed by reference.

    What your book means by them being similar is that passing a pointer by value and passing a reference are usually implemented identically. The difference is purely at the C++ level: with a reference, you do not have the value of the pointer (and hence cannot change it), and it is guaranteed to refer to an actual object (unless you broke your program earlier).

提交回复
热议问题