#include <fstream>
#include <string>
using namespace std;
ofstream out("HowMany.out");
class HowMany {
string name;
static int objectCount;
public:
HowMany(const string str=""):name(str) { objectCount++; }
HowMany( HowMany& X){name=X.name+"COPY";objectCount++; out<<name<<endl;}
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("h");
HowMany::print("after construction of h");
HowMany h2("h2");
out<<"test1........"<<endl;
h2=f(h);
out<<"test2........"<<endl;
HowMany::print("after call to f()");
} ///:~
输出结果为
after construction of h: objectCount = 1
test1........
hCOPY
x argument inside f(): objectCount = 3
hCOPYCOPY
~HowMany(): objectCount = 3
~HowMany(): objectCount = 2
test2........
after call to f(): objectCount = 2
~HowMany(): objectCount = 1
~HowMany(): objectCount = 0