|
From: Alfred P. R. <al...@ya...> - 2005-04-20 17:47:06
|
Hi Francesco, Your array of class objects would be better served if it where a list or vector of class objects instead of an array. Then you can use the iterator features, including list and vector specific swap and sort member functions. If you must use an array of class objects, then there's always the <algorithm> standard template library header. Algorithm has a rich set of functions that include swap, sort, and other useful data manipulation algorithms such as unique, etc. These functions are usually optimized, and work in most instances significantly better than manually coded swap or sort functions. I'm not actually sure what you mean by "deep copy", however, I'm assuming that you mean actual data copying. You shouldn't be copying data to swap it! You should be swapping pointers to the data. Maybe the issue is in using a class class_objects[array_size]; declaration vs. a class *class_objects; declaration, because the overloaded operator= may operate in a different fashion between a pointer and an array element (i.e. class_objects[7], is a pointer, but in machine code is actually a set of pointer arithmetic operations). The class operator= should already be configured to correctly do something like: class *obj_a, *obj_b, *temp; obj_a = new class; ...; temp = obj_a; obj_a = obj_b; obj_b = temp; delete(temp); ... so that should work correctly, ***** however ***** list<class> obj_list; list<class>::iterator obj_iter; obj_list.push_back(obj_a); ... obj_iter = obj_list.begin(); obj_list.sort() or obj_list.sort( compare_function ); ... is easier, more elegant, and uses the optimized features of C++! Hopefully the above helps! Francesco <xtr...@vi...> wrote: Hi everybody, I'm a total beginner and I have the following problem: I have an array of objects instantiated from a class that has member pointers to dynamically allocated data. This class has also the usual overloaded operator=. I have to sort this array and I need to do some swapping. But swapping by "deep copy" seems useless to me in this case, thus is it possible somehow to override the overloaded operator= and use just for the swapping the normal operator =? I could use memcpy for a bitwise copy, but it seems to be significantly slower, especially for small objects. Thanks in advance, Francesco <snip> Alfred P. Reaud |