大家都知道,在c++中,值传递的时候在栈里面会创建一个临时的对象,那么它会不会调用对应的构造函数和析构函数呢?猜想的话,应该是会调用了的...额,可是做了一个测试...从现象中发现只调用了...析构函数,那么到底有没有调用构造函数呢...
#include<iostream>
using namespace std;
class B{
int i;
public:
B()
{
i = 0;
cout<<"construct b..."<<endl;
}
~B()
{
cout<<"destruct b..."<<endl;
}
};
void fun1(B b)
{
;
}
int main()
{
int j;
B b;
fun1(b);
fun1(b);
j = 0;
return 0;
}
额,后来发现其是由一个已经存在的对象创建一个新的对象,做一下修改:
#include<iostream>
using namespace std;
class B{
int i;
public:
B()
{
i = 0;
cout<<"construct b..."<<endl;
}
B(const B &b)
{
i = 0;
cout<<"default copy construct b..."<<endl;
}
~B()
{
cout<<"destruct b..."<<endl;
}
};
void fun1(B b)
{
;
}
int main()
{
int j;
B b;
fun1(b);
fun1(b);
j = 0;
return 0;
}