I am reading Bjarne Stroustrup's book titled "A tour of C++".
The following section is confusing to me:
When a class is a resource handle – that is, when the class is responsible for an object accessed through a pointer – the default member wise copy is typically a disaster.
Member wise copy would violate the resource handle’s invariant. For example, the default copy would leave a copy of a Vector referring to the same elements as the original:
void bad_copy(Vector v1) { Vector v2 = v1; // copy v1’s representation into v2 v1[0] = 2; // v2[0] is now also 2! v2[1] = 3; // v1[1] is now also 3! }
In particular, I do not understand the following:
When
Vector
v1
is passed as a value, not as a reference, how comev2
andv1
both refer to the same memory address.What does the sentence "When a class is a resource handle" means ?