Previous section   Next section

Imperfect C++ Practical Solutions for Real-Life Programming
By Matthew Wilson
Table of Contents
Chapter 14.  Arrays and Pointers


14.5. Arrays Are Always Passed by Address

As described in detail in [Lind1994], variables of nonarray type in C are passed in function arguments by value, and those of array type are passed by address. The same applies by default in C++, except that one can also pass nonarray types in C++ by reference by decorating the argument with the address-of operator &. There's no built-in mechanism in either language for passing arrays by value.



int i;


int ar[10];





void f(int x, int y[10])


{


  x = x + 1;        // i is not affected


  y[0] = y[0] + 1;  // ar is affected


}





f(i, ar);



Though the need is rare, so it can't be considered an imperfection, it can sometimes be desirable to pass an array by value. Thankfully it's ridiculously easy. The contents of structs (and unions and, in C++, classes) are copied by value, so you simply define a struct containing your array and pass that.



int i;


struct int10


{


  int values[10];


}   ar;





void (int x, int10 y)


{


  x = x + 1;                        // i is not affected


  y.values[0] = y. values [0] + 1;  // ar is not affected


}





f(i, ar);



Naturally, in C++ you would generalize, for both type and dimension, in a template



template <typename T, size_t N>


struct array_copy


{


  T values[N];


};



That's it. The C++ compiler will generate default constructor (section 2.2.2), destructor (section 2.2.8), copy constructor (section 2.2.3), and copy assignment operator (section 2.2.4) according to whether T can support those methods on a per-instance basis.

Naturally, the size of any such copyable array is fixed at compile time. If you want a variable sized copyable array, you're best to use std::vector (see section 14.6.4).


      Previous section   Next section