关于《C++编程思想》第一卷中的 错误
最近在看《C++编程思想》中的拷贝构造函数,发现第十一章11.3.1.4节的例子//:C11:HowMany.cpp书中给出结果与我自己运行的结果不同,请各位看一下原因,顺便分析一下构造函数和析构函数的工作原理。附上代码:
#include <iostream>
#include <string>
using namespace std;
class HowMany
{
static int objectCount;
public:
HowMany()
{
objectCount++;
}
static void print(const string& msg = "")
{
if (msg.size() != 0)
{
cout<<msg<<": ";
}
cout<<"objectCount = "<<objectCount<<endl;
}
~HowMany()
{
objectCount--;
print("~HowMany()");
}
};
int HowMany::objectCount = 0;
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);
HowMany::print("after call to f()");
system("pause");
}
after construction of h:objectCount = 1
x argument inside f(): objectCount = 1
~HowMany(): objectionCount = 0
after call to f(): objectionCount = 0
~HowMany(): objectionCount = -1
~HowMany(): objectionCount = -2
after construction of h:objectCount = 1
x argument inside f(): objectCount = 1
~HowMany(): objectionCount = 0
after call to f(): objectionCount = 0