たとえば、以下のコードでは:
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;
// 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);
HowMany::print("after call to f()");
}
コンパイラがHowManyクラスのコピーコンストラクタを自動的に作成せず、f(h)の呼び出しが行われるときにビット単位のコピーが行われるのはなぜですか?
コンパイラがデフォルトのコピーコンストラクタを作成するのはどのような場合で、作成しないのはどのような場合ですか?
次のように出力されます。
hの構築後:objectCount = 1
f()内のx引数:objectCount = 1
〜HowMany():objectCount = 0
f()の呼び出し後:objectCount = 0
〜HowMany():objectCount = -1
〜HowMany():objectCount = -2
よろしくお願いします