zoukankan      html  css  js  c++  java
  • 临时对象

    直接上代码:

    View Code
     1 #include <iostream>
    2 using namespace std;
    3
    4 class B
    5 {
    6 public:
    7 B()
    8 {
    9 cout << "default constructor " << endl;
    10 }
    11 ~B()
    12 {
    13 cout << "destructed" << data << endl;
    14 }
    15 B(int i) : data(i)
    16 {
    17 cout << "constructed by parameter" << data << endl;
    18 }
    19 private:
    20 int data;
    21 };
    22
    23 B play ()
    24 {
    25 B b(1);
    26 return b; // 按值返回
    27 }
    28
    29 void play2(B b) // 按值传参
    30 {
    31 }
    32
    33 void main()
    34 {
    35 B t1 = play();
    36
    37 play2(t1);
    38 }

     输出:

    constructed by parameter1
    destructed1
    destructed1
    destructed1
    请按任意键继续. . .

    a.按值返回和b.按值传参的位置都会产生一个临时对象。a、b是产生临时对象的两种情况。

    问题来了:

       假如有如下代码,那么结果会是什么呢?

    View Code
     1 #include <iostream>
    2 using namespace std;
    3
    4 class B
    5 {
    6 public:
    7 B()
    8 {
    9 cout << "default constructor " << endl;
    10 }
    11 ~B()
    12 {
    13 cout << "destructed" << data << endl;
    14 }
    15 B(int i) : data(i)
    16 {
    17 cout << "constructed by parameter" << data << endl;
    18 }
    19 private:
    20 int data;
    21 };
    22
    23 B play( B b) // 按值传参
    24 {
    25 return b; // 按值返回
    26 }
    27 void main()
    28 {
    29 B t1 = play();
    30
    31 play2(t1);
    32 }

    输出:

    constructed by parameter5
    destructed5
    destructed5
    请按任意键继续. . .

    可能会问,不是应该有3次析构吗? 怎么只有两次。

    这里是编译器对临时对象做了处理,如果参数和返回值是同一对象,那么只产生传参时候的一次临时对象。[自己理解得,不一定正确]

    解决临时对象的方法:

    使用引用。

    View Code
     1 #include <iostream>
    2 using namespace std;
    3
    4 class B
    5 {
    6 public:
    7 B()
    8 {
    9 cout << "default constructor " << endl;
    10 }
    11 ~B()
    12 {
    13 cout << "destructed" << data << endl;
    14 }
    15 B(int i) : data(i)
    16 {
    17 cout << "constructed by parameter" << data << endl;
    18 }
    19 private:
    20 int data;
    21 };
    22
    23 B play( B &b) // 按值传参
    24 {
    25 return b; // 按值返回
    26 }
    27 void main()
    28 {
    29 B t2(5);
    30 B t1 = play(t2);
    31
    32 }



     

  • 相关阅读:
    PTP 接线方式及通讯距离
    串口通信基本概念
    Modbus RTU 通信应用案例
    Modbus 指令
    Modbus RTU新版本指令介绍
    Integer自动装箱和拆箱
    重写hashCode方法,导致内存泄漏
    Dom4j入门
    Java设计模式(9)——观察者模式
    IntelliJ IDEA版本控制——过滤提交文件
  • 原文地址:https://www.cnblogs.com/xuxu8511/p/2419472.html
Copyright © 2011-2022 走看看