Going to Copy Constructor from here Why?

U

utab

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::eek:bjectCount = 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.
 
P

Pavel

Phlip said:
utab wrote:




The FAQ covers "return value optimization":

http://www.parashift.com/c++-faq-lite/ctors.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; }
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,999
Messages
2,570,243
Members
46,836
Latest member
login dogas

Latest Threads

Top