随着下面的程序,我试图用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