所以,这可能是一个令人尴尬的问题。我正在强化我的 C++ 基础知识,但遇到了这个奇怪的案例。
有趣的是,在进入函数时,不会为对象 lb 调用构造函数,但在离开函数时,我推测会为 lb 调用析构函数。
这怎么可能?当它们进入函数时,应该调用构造函数和析构函数。或者,如果只调用析构函数,那么我预计会导致段错误?
#include <iostream>
using namespace std;
class B {
public:
B() {
cout<<"Construct B"<<endl;
}
virtual ~B() {
cout<<"Destruct B"<<endl;
}
};
bool FuncByVal(B lb)
{
return true;
}
int main(int argc, char* argv[])
{
B b;
FuncByVal(b);
return 0;
}
输出是: 构造B 破坏B 破坏B
我在 Windows 8.1 下的 Visual Studio 2012 和 Windows 8.1 下使用 MinGW 的 Eclipse 上进行了测试。
另外,我也在 Linux (eclipse+gcc) 下进行了测试,以确保万无一失。
附注对于按引用复制,输出如我所料,即,同一代码仅调用了一个构造函数调用和一个析构函数。
最佳答案
被调用的是对象的复制构造函数,而不是它的默认构造函数。由于您没有明确定义复制构造函数 compiler defined it implicitly (当然没有输出)。
class B {
public:
B() {
cout<<"Construct B"<<endl;
}
/// Add this
B(const B&) {
cout<<"Copy B"<<endl;
}
virtual ~B() {
cout<<"Destruct B"<<endl;
}
};
关于c++ - 函数参数不调用构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30155262/