• 编译器优化代码研究


    《Effective C++》条款21:

    /**

    * 结论:对自定义类型对象表达式objA*objB = objC;

    * 定义friend MyInt operator*(const MyInt& lhs,const MyInt& rhs)

    * 编译器优化后:operator*()函数内直接在调用接收处构造(此处的匿名临时对象),

    * 然后为该匿名临时对象调用operator=()方法。

    * 避免了operator*()函数内返回值对象的构造和析构成本;

    */

    1. #include "stdio.h"
    2. class MyInt;
    3. MyInt operator*(const MyInt& lhs,const MyInt& rhs);
    4. class MyInt
    5. {
    6. private:
    7. int val;
    8. public:
    9. MyInt(int _val):val(_val)
    10. {
    11. printf("call MyInt(%d)\n",val);
    12. }
    13. MyInt(MyInt& rhs):val(rhs.val)
    14. {
    15. printf("call MyInt(MyInt{%d})\n",val);
    16. }
    17. friend MyInt operator*(const MyInt& lhs,const MyInt& rhs)
    18. {
    19. MyInt rtn = MyInt(lhs.val*rhs.val);
    20. printf("call MyInt operator(const MyInt&,const MyInt&) for local MyInt 0x%lu\n",&rtn); // 0x140702046834832
    21. return rtn;
    22. }
    23. MyInt& operator=(const MyInt& rhs)
    24. { // 令赋值运算符返回bool 而不是MyInt&
    25. printf("call bool operator=(const MyInt&) for MyInt 0x%lu\n",this); // 0x140702046834832
    26. val = rhs.val;
    27. return *this;
    28. }
    29. };
    30. int main(int argc,char* argv[])
    31. {
    32. MyInt objA(3),objB(4),objC(5);
    33. printf("...\n");
    34. objA*objB = objC; // 对objA*objB返回的MyInt&临时匿名对象调用赋值运算符
    35. // |__编译器优化后:operator*()函数内直接在调用接收处(此处的匿名临时对象)构造,然后为该匿名临时对象调用operator=()方法
    36. //if(objA*objB = objC)
    37. //{ // warning: using the result of an assignment as a condition without parentheses [-Wparentheses]
    38. // printf("passed\n");
    39. //}
    40. //3*4=5; // error: expression is not assignable
    41. }

  • 相关阅读:
    【NGINX--2】高性能负载均衡
    MySQL的索引与事务
    pytorch基础操作(1)
    差点送外卖!双非普本的我刷完P8大佬的性能调优手册,终面进阿里
    王学岗音视频开发(二)—————OpenGLES开发实践
    Python+Requests+Pytest+YAML+Allure实现接口自动化
    MIxformerV2的onnx和tensorrt加速
    计划任务备份
    【附源码】Python计算机毕业设计汽车租赁管理系统
    Python文件操作篇
  • 原文地址:https://blog.csdn.net/HayPinF/article/details/134542300