C++ 临时对象

    书上说,参数按值传递和返回值按值传递的时候产生临时对象,而函数按值传递参数的时候,产生临时变量比较好理解,其实就是函数参数的局部变量的生成。返回值生成临时变量有两种情况

   

1 class Test{
2 static int i;
3  public:
4 Test()
5 {
6 cout<<"ctor"<<endl;
7 }
8 Test(const Test&test)
9 {
10 cout<<"copy ctor"<<endl;
11 }
12 ~Test(){
13
14 cout<<"destory.."<<endl;
15 }
16 void print()
17 {
18
19 }
20 };
21
22
23 Test F(Test x)
24 {
25 return x;
26
27 }

情况1:

int main()
{
    Test t1;
    
    Test t2=F(t1);

    return 0;

这种情况下面,t2直接被F函数内部的变量用复制构造函数给构造,不生成临时变量,不存在临时变量的析构

情况2

int main()
{
    Test t1;
    
    Test t2;

     t2=F(t1);

    return 0;
}

这种情况,返回处会生成一个临时变量,在赋值给t2以后,析构掉。F内部的也会析构掉。

原文地址:https://www.cnblogs.com/miniwiki/p/1738794.html