passing an array as a const argument of a method in C++

后端 未结 4 1236
伪装坚强ぢ
伪装坚强ぢ 2020-12-16 19:14

I would like to be able to pass a const array argument to a method in C++.

I know that when you pass an array to method it is the same than passing a pointer to the

4条回答
  •  轮回少年
    2020-12-16 19:38

    Per 3.9.3:2

    Any cv-qualifiers applied to an array type affect the array element type, not the array type (8.3.4).

    and 8.3.4:1

    Any type of the form “cv-qualifier-seq array of N T” is adjusted to “array of N cv-qualifier-seq T”, and similarly for “array of unknown bound of T”.

    Also, per 8.3.5:5

    After determining the type of each parameter, any parameter of type “array of T” or “function returning T” is adjusted to be “pointer to T” or “pointer to function returning T,” respectively.

    That means that within a function taking an array parameter, the parameter type is actually a pointer, and because of 3.9.3:2 the pointer is non-cv-qualified:

    void foo(const int parameter[10]) {
        parameter = nullptr;   // this compiles!
    }
    

    This does not affect the type of the function itself, because of another clause in 8.3.5:5

    After producing the list of parameter types, any top-level cv-qualifiers modifying a parameter type are deleted when forming the function type.

    Thus if you want to be able to pass an array with cv qualifiers, it must be by reference:

    void foo(const int (¶meter)[10]);
    

提交回复
热议问题