【分析】

i++与++i哪个效率更高?

(1)在内建数据类型的情况下,效率没有区别;

(2)在自定义数据类型Class的情况下,++i效率更高!

自定义数据类型的情况下:++i返回对象的引用;i++总是要创建一个临时对象,在退出函数时还要销毁它,而且返回临时对象的值时还会调用其拷贝构造函数。

【代码】

 C++ Code 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
 
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <vector>
#include <iostream>
using namespace std;

class Integer
{
public:
    Integer(int value): v(value)
    {
        cout << "default constructor" << endl;
    }
    Integer(const Integer &other)
    {
        cout << "copy constructor" << endl;
        v = other.v;
    }
    Integer &operator=(const Integer &other)
    {
        cout << "copy assignment" << endl;
        v = other.v;
        return *this;
    }

// ++i  first +1,then return new value
    Integer &operator++()
    {
        cout << "Integer::operator++()" << endl;
        v++;
        return *this;
    }

// i++  first save old value,then +1,last return old value
    Integer operator++(int)
    {
        cout << "Integer::operator++(int)" << endl;
        Integer old = *this;
        v++;
        return old;
    }

void output()
    {
        cout << "value " << v << endl;
    }
private:
    int v;
};

void test_case()
{
    Integer obj();
    Integer obj2 = obj;
    Integer obj3();
    obj3 = obj;
    cout << "--------------" << endl;
    cout << "++i" << endl;
    ++obj;
    obj.output();
    cout << "i++" << endl;
    obj++;
    obj.output();
}

int main()
{
    test_case();
    ;
}
/*
default constructor
copy constructor
default constructor
copy assignment
--------------
++i
Integer::operator++()
value 11
i++
Integer::operator++(int)
copy constructor
value 12
*/

最新文章

  1. Onsen UI – 新鲜出炉的 PhoneGap 界面框架
  2. MVC数据验证原理及自定义ModelValidatorProvider实现无编译修改验证规则和错误信息
  3. 资源搜集:Git精品文章推荐,常年更新
  4. 关于ImageMagick出现无效参数(invalid parameter)的解决方法
  5. c# 搭建服务端 传输协议(2)
  6. Ubuntu 13.04/12.10安装Oracle 11gR2图文教程(转)
  7. OpenCV2第一个马拉松8环——画一个柱状图
  8. GridControl基础设置(一)
  9. [NOI2017]泳池
  10. Docker Dockerfile
  11. web移动端区分Android或者ios系统
  12. Android--UI之ListView
  13. WebApi参数传递实例
  14. JS计算前一天或后一天,前一月后一月
  15. cxRichEdit1获取EXCEL的区域图片
  16. css3统一元素的宽和高
  17. java读取记事本文件第一个字符遇到的一个坑
  18. Mac下终端(terminal)的一些快捷键
  19. kendo-ui的MVVM模式
  20. SSH电力项目四-显示首页

热门文章

  1. 重构alert,confirm
  2. cxf3.x +spring 3.x(4.x)+ maven 发布webservice 服务
  3. JS组件系列——Bootstrap Table 表格行拖拽(二:多行拖拽)
  4. C#进阶系列——DDD领域驱动设计初探(七):Web层的搭建
  5. mariadb
  6. CREATE TABLE 表名 AS SELECT 语句
  7. 显式意图启动一个Activity
  8. Xcode调试技巧(断点和重构)
  9. Spring IOC容器创建对象的方式
  10. js获取当前坐标