How are arrays passed?

前端 未结 3 1811
悲哀的现实
悲哀的现实 2020-12-14 17:36

Are arrays passed by default by ref or value? Thanks.

3条回答
  •  感情败类
    2020-12-14 17:48

    First, you cannot pass an array by value in the sense that a copy of the array is made. If you need that functionality, use std::vector or boost::array.

    Normally, a pointer to the first element is passed by value. The size of the array is lost in this process and must be passed separately. The following signatures are all equivalent:

    void by_pointer(int *p, int size);
    void by_pointer(int p[], int size);
    void by_pointer(int p[7], int size);   // the 7 is ignored in this context!
    

    If you want to pass by reference, the size is part of the type:

    void by_reference(int (&a)[7]);   // only arrays of size 7 can be passed here!
    

    Often you combine pass by reference with templates, so you can use the function with different statically known sizes:

    template
    void by_reference(int (&a)[size]);
    

    Hope this helps.

提交回复
热议问题