Duc*_*ers 2 c++ constructor destructor pass-by-value
所以,这可能是一个令人尴尬的问题.我正在重新执行我的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;
}
Run Code Online (Sandbox Code Playgroud)
输出为:构造B Destruct B Destruct B.
我在Windows 8.1下使用Visual Studio 2012进行了测试,在Windows 8.1下使用MinGW在Eclipse上进行了测试.
另外,我在Linux(eclipse + gcc)下进行了测试,这是肯定的.
ps用于按引用复制输出,就像我预期的那样,即只有一个构造函数调用和一个析构函数被调用相同的代码.
所谓的是对象的复制构造函数,而不是它的默认构造函数.由于您没有显式定义复制构造函数,因此编译器会隐式定义它(当然没有输出).
class B {
public:
B() {
cout<<"Construct B"<<endl;
}
/// Add this
B(const B&) {
cout<<"Copy B"<<endl;
}
virtual ~B() {
cout<<"Destruct B"<<endl;
}
};
Run Code Online (Sandbox Code Playgroud)