🚀 go-pugleaf

RetroBBS NetNews Server

Inspired by RockSolid Light RIP Retro Guy

Article View: comp.std.c++
Article #947

Default copy constructor not making a copy

#947
From: Michael Klein
Date: Mon, 25 Feb 1991 19:56
50 lines
1931 bytes
Can someone explain why the two classes defined below exhibit different
behavior?  The class without the default copy constructor does not make
a copy of the *this argument for the + operator.  There is a related
comment in Ellis & Stroustrup (12.6.1): "Had no copy constructor been
declared...all would have happened exactly as before because a copy
constructor would have been generated.  Again, a good compiler would
eliminate the use of the generated copy constructor."  I'm not convinced
that this statement applies in this case.  Any enlightenment on this
subject would be welcome.  I'm using ATT C++ 2.0 on a Sparc.


#include <iostream.h>
#include <iomanip.h>

class NoCopy {
public:
  int x;
  NoCopy (int a) { x = a; };
  NoCopy &operator +=(int a) { x += a; return *this; };
  NoCopy  operator + (int a) { return NoCopy(*this) += a; };
};

class Copy {
public:
  int x;
  Copy(const Copy &c) : x(c.x) {};
  Copy (int a) { x = a; };
  Copy &operator =(int a) { x = a; return *this; };
  Copy &operator +=(int a) { x += a; return *this; };
  Copy  operator + (int a) { return Copy(*this) += a; };
};

void main()
{
  NoCopy xNo(1), xNo2(-1);
  Copy xYes(2), xYes2(-2);
  cout << "No=" << xNo.x << " Yes=" << xYes.x << endl;
  cout << "No2=" << xNo2.x << " Yes=" << xYes2.x << endl;
  xNo2 = xNo + 2;
  xYes2 = xYes + 2;
  cout << "No=" << xNo.x << " Yes=" << xYes.x << endl;
  cout << "No2=" << xNo2.x << " Yes=" << xYes2.x << endl;
}

Output of the program:
No=1 Yes=2
No2=-1 Yes=-2
No=3 Yes=2
No2=3 Yes=4
Technical Details
Message-ID: <253@blsouth.UUCP>
Path: arc1-ca.pugleaf.net!utzoo!attcan!uunet!samsung!emory!emcard!gatech!sbmsg1!blsouth!klein

Show Full Headers
Complete Article Headers
Path: arc1-ca.pugleaf.net!utzoo!attcan!uunet!samsung!emory!emcard!gatech!sbmsg1!blsouth!klein
From: klein@blsouth.UUCP (Michael Klein)
Newsgroups: comp.std.c++
Subject: Default copy constructor not making a copy
Message-ID: <253@blsouth.UUCP>
Date: 25 Feb 91 19:56:34 GMT
Reply-To: klein@blsouth.UUCP (Michael Klein)
Organization: BellSouth Services, Atlanta Ga.
Lines: 50