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 }



     

  • 相关阅读:
    HTML 5 --- 移动端viewport:
    Mac Apache 启动Web工程(webserver):
    java对xml文件做增删改查------摘录
    google code 上传源码
    一段下载文件的源码
    delphi 截取指定符号之间的字符串-随机读取
    从github 读取 绝对地址 ini文件
    使用Delphi读取网络上的文本文件,html文件
    ubuntu下新立得(synaptic)软件包管理器安装
    ubuntu下卸载旧Mysql并安装新Mysql(升级)
  • 原文地址:https://www.cnblogs.com/xuxu8511/p/2419472.html
Copyright © 2011-2022 走看看