TITLE: backdoor use of memcpy (Newsgroups: comp.lang.c++.moderated) PROBLEM: "Roger L. Cauvin" >In a previous message, I asked whether the following was legal C++ and >successfully shallow-copied object[0]: ... code using memcpy deleted ... >If I have an array of a thousand objects, and I wish to shift all of the >items between indices 0 to 998 up by one index; i.e. so that they reside >at indices 1 to 999, I have two ways of implementing the shift: > >1. Call the assignment operator on every single item. The assignment >operator would be called 999 times. ... > >2. Call memmove once to shift all of the items efficiently. ... REPONSE: clamage@Eng.Sun.COM (Steve Clamage), 16 May 96 The *reason* for wanting to move an object in memory doesn't affect the validity of doing so. My original comment about no language guarantees unless you have a "bag of bits" still applies. Scott Howlett correctly pointed out that you cannot (in general) know what the copy constructor and assignment operator might need to do that is special. He also presented a killer example (which I wish I had thought of): An object which contains a pointer to itself cannot be correctly moved with memcpy. Don't wear blinders and trudge down this path: 1. I have a C-style array of objects. 2. I need to shift the objects in the array. 3. Shifting is expensive if I use repeated assignment. 4. Therefore I need to bypass assignment and use memcpy. Take a broader look at the problem. A number of people pointed out other approaches. A quick observation: Copying doesn't have to be expensive. If you use reference-counted objects, copying is cheap, although other operations become more expensive. This is one of many design tradeoffs, and addresses #3 above. Addressing #1 above, a more fundamental observation is that a C-style array of nontrivial objects is almost never appropriate. Other choices are almost always better. Someone suggested an array of pointers instead of an array of class objects. Addressing #2 above, someone else suggested an array class that hides the details of the array representation. You should not care whether the objects are physically moved, as long as indexed access to them behaves according to the semantics you want. You probably don't even have to design and write an array class yourself. The C++ standard library has many predefined array-like container classes.