Path: utzoo!utgpu!jarvis.csri.toronto.edu!mailrus!csd4.csd.uwm.edu!gem.mps.ohio-state.edu!tut.cis.ohio-state.edu!att!dptg!ulysses!andante!alice!shopiro From: shopiro@alice.UUCP (Jonathan Shopiro) Newsgroups: comp.lang.c++ Subject: Re: copy objects to another location Summary: use the copy-constructor X::X(const X&) to copy objects Message-ID: <9875@alice.UUCP> Date: 10 Sep 89 01:30:10 GMT References: <14265@polyslo.CalPoly.EDU> Distribution: usa Organization: AT&T Bell Laboratories, Murray Hill NJ Lines: 42 In article <14265@polyslo.CalPoly.EDU>, ttwang@polyslo.CalPoly.EDU (Thomas Wang) writes: > I have discovered an interesting issue during the implementation of my > garbage collection project. > > There does not appear to be a portable way to copy an object from one > memory location to another. The operator '=' might be overloaded, so > I cannot depend on it for copying. > The constructor X::X(const X&) has a special position in the language in that it is used for copying objects. If X::X(const X&) is not declared, but X::X(X&) is, then the latter becomes the copy-constructor. The copy- constructor is invoked when you initialize an X from another X, most commonly when passing an X to a function, or returning an X from a function. To move an object, you would probably use the copy-constructor with the placement allocation syntax, as in the following example: void move(const X& obj) // obj is the object to be moved { void* vp = ; // now vp contains the address where the copy of obj // is to go new (vp) X(obj); // invokes the copy-constructor obj.X::~X(); // invoke the destructor (without // de-allocating storage) on the old copy } As it said in my old Sail manual, you had better know what you are doing, or be a good sport. This is not for the faint of heart. In a subsequent article, Cliff Beshers suggests using memcpy to copy objects. This will often work, but some objects do not permit bitwise copying, and they will trip you up. The compiler will synthesize a copy-constructor if you don't supply any constructors for your class, and if bitwise copying is appropriate for your class, that's what it will come up with. So use the copy-constructor, and you get the best of both worlds. -- Jonathan Shopiro AT&T Bell Laboratories, Warren, NJ 07060-0908 research!shopiro (201) 580-4229