Path: utzoo!utgpu!watserv1!watmath!att!att!linac!uwm.edu!cs.utexas.edu!milano!cadillac!vaughan@mcc.com From: vaughan@mcc.com (Paul Vaughan) Newsgroups: comp.lang.c++ Subject: Re: Constructor called with reference to self? Message-ID: <12822@cadillac.CAD.MCC.COM> Date: 3 Nov 90 19:42:38 GMT References: Sender: news@cadillac.CAD.MCC.COM Reply-To: vaughan@mcc.com (Paul Vaughan) Organization: MCC VLSI CAD Program Lines: 51 In-reply-to: tom@ssd.csd.harris.com (Tom Horsley) From: tom@ssd.csd.harris.com (Tom Horsley) Given a class that looks like: class someclass { public: someclass(someclass& arg); ... } Is it ever possible with a correctly functioning C++ compiler for your program to reach the body of the if statement in the following copy constructor: someclass::someclass(someclass& arg) { if (this == &arg) { // Can I get here? } } Yes and No. I agree with you that it generally shouldn't happen, but here is a case where it can. #include class A { public: A() {} A(A& a) { if( this == &a) cout << "copying myself\n"; } }; main() { A* a1 = new A; delete a1; A* a2 = new A(*a1); // <= using a dead object here } Both g++ and sun cfront 2.0 print "copying myself" on this one, but that has more to do with the malloc/free package than anything else. The various compilers differ in the details of when temporary objects created as arguments in expressions get deleted. This might account for why it works differently under different compilers. Also, note that constructors don't exactly get raw bits--all members have been constructed and the constructor initialization list has been run before the constructor body is run. But, basically, a copy constructor should never find itself copying itself. Paul Vaughan, MCC CAD Program | ARPA: vaughan@mcc.com | Phone: [512] 338-3639 Box 200195, Austin, TX 78720 | UUCP: ...!cs.utexas.edu!milano!cadillac!vaughan