By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
432,035 Members | 1,471 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 432,035 IT Pros & Developers. It's quick & easy.

Going to Copy Constructor from here Why?

P: n/a
Dear all, I have got a simple example to demonstrate the need for copy
construction but one point is not clear to me. When returning from the
function in main h2 is not constructed why? I marked that point and
that is also obvious from the output

#include <fstream>
#include <string>
using namespace std;
ofstream out("HowMany.out");

class HowMany {
static int objectCount;
public:
HowMany() { objectCount++; }
static void print(const string& msg = "") {
if(msg.size() != 0) out << msg << ": ";
out << "objectCount = "
<< objectCount << endl;
}
~HowMany() {
objectCount--;
print("~HowMany()");
}
};

int HowMany::objectCount = 0;

// Pass and return BY VALUE:
HowMany f(HowMany x) {
x.print("x argument inside f()");
return x;
}

int main() {
HowMany h;
HowMany::print("after construction of h");
HowMany h2 = f(h);
//////////////////////////////////////////// THIS POINT
HowMany::print("after call to f()");
} ///:~

The output:

after construction of h: objectCount = 1
x argument inside f(): objectCount = 1
~HowMany(): objectCount = 0
after call to f(): objectCount = 0
~HowMany(): objectCount = -1
~HowMany(): objectCount = -2

Many Thanks.

Apr 23 '06 #1
Share this Question
Share on Google+
2 Replies


P: n/a
utab wrote:
Dear all, I have got a simple example to demonstrate the need for copy
construction but one point is not clear to me. When returning from the
function in main h2 is not constructed why?


The FAQ covers "return value optimization":

http://www.parashift.com/c++-faq-lit....html#faq-10.9

Always Google the FAQ before posting!

--
Phlip
http://www.greencheese.org/ZeekLand <-- NOT a blog!!!
Apr 23 '06 #2

P: n/a
Phlip wrote:
utab wrote:

Dear all, I have got a simple example to demonstrate the need for copy
construction but one point is not clear to me. When returning from the
function in main h2 is not constructed why?

The FAQ covers "return value optimization":

http://www.parashift.com/c++-faq-lit....html#faq-10.9

Always Google the FAQ before posting!

I don't believe it has to do with the optimization. It is just that
other 2 instances are created by the language-gentrated copy constructor
rather than by the default constructor -- and in that generated
constructor, object count is not incremented. In fact, from the fact
there are 2 unmatched decrements of objectCount, we can conclude that no
optimization takes place in this particular case.

To see the construction, just add a copy constructor to the class, e.g.:

HowMany(const HowMany &) { ++objectCount; }
Apr 24 '06 #3

This discussion thread is closed

Replies have been disabled for this discussion.