我正在通过 Thinking in C++-Bruce Eckel 中的这个特定示例。我可以理解语句 1(在评论中提到)和语句 2 ,但是即使函数声明和定义也没有返回,我也很难理解语句 3需要返回一个对象以用于复制目的。现在这里实际发生了什么?对于其他两个陈述(1和2),我可以推断出编译器阻止了位复制,因为我们在类中指定了一个复制构造函数,而是通过我们为函数内部传递的对象以及函数返回的对象定义的复制构造函数来处理它。就在函数结束之前,函数内的临时对象被复制为返回值,然后被破坏。我是对的吗?
#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");//statement 1
out << "Entering f()" << endl;
HowMany2 h2 = f(h);//statement 2
h2.print("h2 after call to f()");
out << "Call f(), no return value" << endl;
f(h);//statement 3
out << "After call to f()" << endl;
}
根据 Eckel ,输出为:
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
h2 after call to f()
h copy copy: objectCount = 2
Thinking in C++ www.BruceEckel.com
Call f(), no return value
HowMany2(const HowMany2&)
h copy: objectCount = 3
x argument inside f()
h copy: objectCount = 3
Returning from f()
HowMany2(const HowMany2&)
h copy copy: objectCount = 4
~HowMany2()
h copy: objectCount = 3
~HowMany2()
h copy copy: objectCount = 2
After call to f()
~HowMany2()
h copy copy: objectCount = 1
~HowMany2()
h: objectCount = 0
还有为什么我们不能为返回值分配额外的存储空间,以便我们可以在函数调用之前将它们存储在那里。它可以替代使用引用吗?先感谢您!!!