Birt wrote:
My understanding about defining your own copy and assignment constructors is
whenever there is a member of pointer type.
Is this true or is there any exception to this"rule"?
How about when you define a class which doesn't have a pointer type variable
as member and this class could be derived,
and a new member of pointer type could be added in the future?
Does this mean that all classes that will be inherited in the future
should be defined with its copy and assignment constructor?
Is it right to say that either compiler-generated or programmer-provided
copy and assignment constructors
will do member-wise object copying or assignment all the time?
Is there any place in C++ that copying between objects could be bit-by-bit?
cat doubleVector.cc
#include <cassert>
#include <cstdlib>
class doubleVector {
private:
// representation
double* array;
size_t size;
public:
// functions
size_t extent(void) const {
return size; }
// operators
operator double*(void) const {
return array; }
operator double*(void) {
return array; }
const
double& operator[](size_t j) const {
return array[j]; }
double& operator[](size_t j) {
return array[j]; }
doubleVector& operator=(const doubleVector& v) {
doubleVector& u = *this;
assert(extent() == v.extent());
for (size_t j = 0; j < extent(); ++j)
u[j] = v[j];
return u;
}
// constructors
doubleVector(void): // default
array(0), size(0) { }
explicit
doubleVector(size_t n): // explicit
array(new double[n]), size(n) { }
//doubleVector(const doubleVector& v): // copy shallow
// array((double*)v), size(v.extent()) { }
doubleVector(const doubleVector& v): // copy deep
array(new double[v.extent()]),
size(v.extent()) { *this = v; }
};
In this example, an object of type doubleVector contains
a pointer to an array of double precision floating point numbers
and the extent of that array.
The *semantics* of type doubleVector require a "deep" copy
of the right hand side (rhs) into the left hand side (lhs)
and that the extent of the rhs and lhs are equal.
The semantics also require a deep copy constructor.
The default assignment operator and copy constructors
won't do the deep copy. The programmer is obliged to override them
with definitions that do the deep copy.