不考虑任何编译器优化(如:NRVO),下述代码的第10行会发生
#include <stdio.h>
class B{
};
B func(const B& rhs){
return rhs;
}
int main(int argc, char **argv){
B b1, b2;
b2 = func(b1); //10
} #include <stdio.h>
class B{
};
B func(const B& rhs){
return rhs;
}
int main(int argc, char **argv){
B b1, b2;
b2 = func(b1); //10
} 一次默认构造函数,一次拷贝构造函数,一次析构函数,一次(拷贝赋值运算符)operator=
二次拷贝构造函数,一次析构函数
一次(拷贝赋值运算符)operator=,一次析构函数
一次拷贝构造函数,一次析构函数,一次(拷贝赋值运算符)operator=
#include <stdio.h>classB{public:B(){printf("B constructor.\n");}~B(){printf("B destructor.\n");}B(constB& other){printf("B copy constructor.\n");}B& operator =(B& rhs){printf("operator = .\n");returnrhs;}};B func(constB& rhs){printf("function func.\n");returnrhs;}intmain(intargc,char**argv){B b1,b2;{b2=func(b1);}getchar();return0;}
#include <stdio.h>
class B{
};
B func(const B& rhs){
return rhs;
}
int main(int argc, char **argv){
B b1, b2;
b2 = func(b1); //10
}
第十行所执行的动作分析: 1、func(b1);b1引用传递给rhs,不会发生什么。 2、return rhs;返回值是以B类型的值的方式返回,即B temp = rhs;temp调用拷贝构造函数。 3、b2 = func(b1);也就是b2 = temp;此时b2调用operator=赋值操作符函数 4、当b2 = func(b1);执行完后,temp调用析构释放
class B
{
public:
//构造函数
B()
{
cout<<"B()"<<endl;
}
//拷贝构造
B(const B& b)
{
cout<<"&B()"<<endl;
}
//析构函数
~B()
{
cout<< "~B()"<<endl;
}
};
B func(const B &res)
{
cout<<"func()"<<endl;
return res;
}
int main() {
B b1,b2;
b2=func(b1);
system("pause");
return 0;
}