一、有趣的问题

[C++]23.神秘的临时对象


输出结果:(是一个随机值)

[C++]23.神秘的临时对象

发生了什么:

[C++]23.神秘的临时对象


思考

[C++]23.神秘的临时对象

答案

[C++]23.神秘的临时对象

代码段Test(0)产生临时对象:

    Test() {
        Test(0); //想直接调用参数构造函数;此时产生临时对象
		         //等价于 Test(0) 不存在
    }

添加init()函数避免产生邻时对象:

class Test {
    int mi;
    
    void init(int i) //为了不让程序产生临时对象,
    {                //实际工程中添加init()函数
        mi = i;
    }
public:
    Test(int i) {
        init(i);
    }
    Test() {
        init(0);
    }
    void print() {
        printf("mi = %d\n", mi);
    }
};

## 二、现代编译器的行为:

[C++]23.神秘的临时对象

三、编程实验:神秘的临时对象

#include <stdio.h>

class Test
{
    int mi;
public:
    Test(int i)
    {
        printf("Test(int i) : %d\n", i);
        mi = i;
    }
    Test(const Test& t)
    {
        printf("Test(const Test& t) : %d\n", t.mi);
        mi = t.mi;
    }
    Test()
    {
        printf("Test()\n");
        mi = 0;
    }
    int print()
    {
        printf("mi = %d\n", mi);
    }
    ~Test()
    {
        printf("~Test()\n");
    }
};

Test func()
{
    return Test(20);
}

int main()
{
    Test t = Test(10); // ==> Test t = 10;
	                   //1.生成临时对象 2.用临时对象初始化化 t 对象
					   //发现:编译器没有调用拷贝构造函数
    
	Test tt = func();  // 等价于:==> Test tt = Test(20); ==> Test tt = 20;
    
    t.print();
    tt.print();
    
	//临时对象会降低效率
    return 0;
}

##四、小结:

[C++]23.神秘的临时对象


本文为听课笔记,课程地址为:

https://item.taobao.com

相关文章:

  • 2022-12-23
  • 2021-07-12
  • 2021-11-18
  • 2022-12-23
  • 2022-12-23
  • 2018-03-16
  • 2021-10-01
  • 2022-12-23
猜你喜欢
  • 2021-11-30
  • 2022-12-23
  • 2021-06-15
  • 2022-12-23
  • 2022-03-06
相关资源
相似解决方案