隨着下面的程序,我試圖用copy ctor進行試驗,有一點不清楚,當函數f()
返回時應該使用copy-ctor爲h2
創建一個新對象,但是我猜這是通過臨時對象完成的,該對象使用對象的構造器然後進行復制,但是銷燬輸出顯示我在這個推理上是錯誤的...對此問題有一些澄清...)臨時和複製構造函數
#include <fstream>
#include <string>
using namespace std;
ofstream out("HowMany2.out");
class HowMany2 {
string name; // Object identifier
static int objectCount;
public:
HowMany2(const string& id = "") : name(id) {
++objectCount;
print("HowMany2()");
}
~HowMany2() {
--objectCount;
print("~HowMany2()");
}
// The copy-constructor:
HowMany2(const HowMany2& h) : name(h.name) {
name += " copy";
++objectCount;
print("HowMany2(const HowMany2&)");
}
void print(const string& msg = "") const {
if(msg.size() != 0)
out << msg << endl;
out << '\t' << name << ": "
<< "objectCount = "
<< objectCount << endl;
}
};
int HowMany2::objectCount = 0;
// Pass and return BY VALUE:
HowMany2 f(HowMany2 x) {
x.print("x argument inside f()");
out << "Returning from f()" << endl;
return x;
}
int main() {
HowMany2 h("h");
out << "Entering f()" << endl;
HowMany2 h2 = f(h);
}
輸出
HowMany2()
h: objectCount = 1
Entering f()
HowMany2(const HowMany2&)
h copy: objectCount = 2
x argument inside f()
h copy: objectCount = 2
Returning from f()
HowMany2(const HowMany2&)
h copy copy: objectCount = 3
~HowMany2()
h copy: objectCount = 2 // Confused here !!!! why not h copy copy
~HowMany2()
h copy copy: objectCount = 1
~HowMany2()
h: objectCount = 0
Thx爲澄清,比這個代碼字符串有什麼不同a =「a」;編譯器通過調用帶有c風格字符串的字符串構造函數創建一個臨時文件,並使用Ctl初始化一個臨時拷貝來複制C++初始化第13章,這是提問時的推理,但不同的實現可以做代碼中的不同事物... – 2010-12-19 18:26:16