Indiana

I use memcpy in my Array2D class which is used for storing elements of type: unsigned char, double, float, etc...
but also for type RGB which is a class type. My question is if it safe to copy objects of some class using memcpy

Up till now everything was ok, I did not have any problems with that, but I saw some comments on other forums that this may lead to unexpected results.


Code Block

template <class T>
class Array2D {
protected:
T* mem_begin_;
protected:
// data
T** mm_;
// rows
int rows_;
// cols
int cols_;
//
protected:
static int allocated_;
static int deallocated_;
protected:
// allocate continuous 2D array
T** alloc2DArray(int rows, int cols) {
mm_ = new T*[rows];
mem_begin_ = new T[cols*rows];
//
register int y;
for (y = 0; y < rows; y++) {
mm_[y] = (mem_begin_ + y*cols);
}
allocated_++;
return mm_;
}
// free
void free2DArray() {
//delete member variables
delete[] this->mm_;
delete[] this->mem_begin_;
deallocated_++;
};
// init
void init(int rows, int cols) {
this->rows_ = rows;
this->cols_ = cols;
alloc2DArray(rows, cols);
}
void initAndCopy(T* src, int rows, int cols) {
this->rows_ = rows;
this->cols_ = cols;
alloc2DArray(rows, cols);
memcpy(this->mem_begin_, src, cols*rows*sizeof(T));
}
void copy(T* src, int rows, int cols) {
ASSERT((rows_ == rows) && (cols_ == cols));
memcpy(elements_, elements(), size()*sizeof(T));
}
// raw
T* getRawData() const { return this->mem_begin_; };
T* copyRawData() const {
T* elements_ = new T[size()];
memcpy(elements_, elements(), size()*sizeof(T));
return elements_;
}
public: // constructors
explicit Array2D(int rows, int cols) {
init(rows, cols);
}
explicit Array2D(const IRect& r) {
init(r.rows(), r.cols());
}
explicit Array2D(T* mm, int rows, int cols) {
initAndCopy(mm, rows, cols);
}
explicit Array2D(T* mm, const IRect& r) {
initAndCopy(mm, r.rows(), r.cols());
}
// copy constructor
Array2D(const Array2D& a2) {
initAndCopy(a2.elements(), a2.rows(), a2.cols());
}
// constructor needed for casting
template <class CastType>
Array2D(const Array2D<CastType>& a) {
init(a.rows(), a.cols());

T* data_ = this->elements();

CastType* data_ct = a.elements();
for (int i = 0; i < a.size(); i++) {
data_[i] = T(data_ct[i]);
}
}
// des
virtual ~Array2D() {
free2DArray();
};

//etc...

}




Re: Visual C++ Language memcpy for objects

Bruno van Dooren

No, memcpy is generally not safe for copying objects.

While it is safe if your members are just POD (plain old data), it will be very bad if your members are other objects like strings, streams, ...

A bit by bit memory copy will be performed and this will lead to memory corruption and crashes.

Even if your class has no object members, one day that class might change and suddenly your program starts to misbehave and you have to do a lot of refactoring.

If you work with classes, use copy constructors and assignment operators to implement proper copy behavior.