From "Programming: Principles and Practices using C++ - Bjarne Stroustrup" example on copying arrays:
18.3.1 Copy constructors
class vector {
int sz; // the size
double* elem; // a pointer to the elements
public:
vector(int s) :
sz { s }, elem { new double[s] } {
for (int i = 0; i < sz; ++i)
elem[i] = 0.0; // initialize
} // constructor
~vector() {
delete[] elem;
} // destructor
int size() const {
return sz;
} // the current size
double get(int n) const {
return elem[n];
} // access: read
void set(int n, double v) {
elem[n] = v;
} // access: write
vector(const vector& arg)
// allocate elements, then initialize them by copying
:
sz { arg.sz }, elem { new double[arg.sz] } {
copy(arg.elem, arg.elem + arg.sz, elem); // std::copy(); see §B.5.2
}
};
int main(int argc, char ** argv) {
vector v(3); // define a vector of 3 elements
v.set(2, 2.2); // set v[2] to 2.2
vector v2 = v;
v.set(1, 99); // set v[1] to 99
v2.set(0, 88); // set v2[0] to
cout << v.get(0) << ' ' << v2.get(1);
return 0;
}
Why are the actual array members copied and not just their addresses? elem is a pointer and is not de-referenced in the copy command.