| www.delorie.com/archives/browse.cgi | search |
| From: | "A. Sinan Unur" <asu1 AT cornell DOT edu> |
| Newsgroups: | comp.os.msdos.djgpp |
| Subject: | Re: Can You help me about djgpp with c++ |
| Date: | 10 Sep 2001 23:28:22 GMT |
| Organization: | Cornell University |
| Lines: | 81 |
| Sender: | asu1 AT cornell DOT invalid (on slip-32-102-40-254.ny.us.prserv.net) |
| Message-ID: | <Xns9118C615515F0ASINANUNUR@132.236.56.8> |
| References: | <Pine DOT SUN DOT 3 DOT 91 DOT 1010910090923 DOT 18194E-100000 AT is> <003201c13a3f$053b2f40$aa7ba8c0 AT fuego> |
| NNTP-Posting-Host: | slip-32-102-40-254.ny.us.prserv.net |
| X-Trace: | news01.cit.cornell.edu 1000164502 16129 32.102.40.254 (10 Sep 2001 23:28:22 GMT) |
| X-Complaints-To: | usenet AT news01 DOT cit DOT cornell DOT edu |
| NNTP-Posting-Date: | 10 Sep 2001 23:28:22 GMT |
| User-Agent: | Xnews/4.06.22 |
| To: | djgpp AT delorie DOT com |
| DJ-Gateway: | from newsgroup comp.os.msdos.djgpp |
| Reply-To: | djgpp AT delorie DOT com |
"Gorden" <gorden AT ms9 DOT url DOT com DOT tw> wrote in
news:003201c13a3f$053b2f40$aa7ba8c0 AT fuego:
> I Buy a book (Teach Yourself C++, 3rd Edition By Herbert Schildt)
> inside have a C++ smaple
I modified your code as follows:
#include <iostream>
class Sample
{
private:
int i;
public:
Sample() { std::cout << "Constructor" << std::endl; }
Sample(const Sample& src)
{
i = src.i;
std::cout << "Copy constructor" << std::endl;
}
Sample& operator=(const Sample& rhs)
{
if( &rhs != this )
{
i = rhs.i;
}
std::cout << "Assignment operator" << std::endl;
return *this;
}
~Sample() { std::cout << "Destructor " << std::endl; }
void set(int n) { i = n ; }
int get(void ) { return i; }
};
int test(Sample o)
{
return o.get() * o.get();
}
int main(void)
{
Sample aSample;
aSample.set(10);
std::cout << test(aSample) << std::endl;
return 0;
}
When compiled and run, this code produces the following:
C:\var>gpp t.cc -o t.exe -Wall
C:\var>t
Constructor
Copy constructor
Destructor
100
Destructor
You can see that your original code was missing the copy constructor, and
the compiler was creating an extra copy for the test function call.
Incidentally, compiling your original code with -O3 gets rid of this extra
copy.
I guess the compiler, in the absence of aggressive optimization or a copy
constructor is creating am extra temporary.
Sinan.
--
--------------------------------
A. Sinan Unur
http://www.unur.com/
| webmaster | delorie software privacy |
| Copyright © 2019 by DJ Delorie | Updated Jul 2019 |