设为首页 加入收藏

TOP

8.5.1 避免不必要的复制操作(2)
2013-10-07 16:07:29 来源: 作者: 【 】 浏览:54
Tags:8.5.1 避免 必要 复制 操作

8.5.1  避免不必要的复制操作(2)

此示例产生如下输出:
 

  1. Constructor called.  
  2. Constructor called.  
  3. Constructor called.  
  4. Executing: motto3 = motto1 + motto2  
  5. Add operator function called.  
  6. Constructor called.  
  7. Copy constructor called.  
  8. Destructor called.  
  9. Assignment operator function called.  
  10. Destructor called.  
  11. Done!!  
  12. Executing: motto3motto3 = motto3 + motto1 + motto2  
  13. Add operator function called.  
  14. Constructor called.  
  15. Copy constructor called.  
  16. Destructor called.  
  17. Add operator function called.  
  18. Constructor called.  
  19. Copy constructor called.  
  20. Destructor called.  
  21. Assignment operator function called.  
  22. Destructor called.  
  23. Destructor called.  
  24. Done!!  
  25. motto3 contains -  
  26. The devil takes care of his own. If you sup with the devil use a long spoon.  
  27. The devil takes care of his own. If you sup with the devil use a long spoon.  
  28. Destructor called.  
  29. Destructor called.  
  30. Destructor called.  

示例说明

我们感兴趣的第一条语句是:

  1. motto3 = motto1 + motto2;              // Use new addition operator 

这条语句调用operator+()将motto1和motto2相加,此运算符函数调用构造函数来创建要返回的临时对象。然后,复制构造函数复制返回的对象,可以从析构函数调用中看到,析构函数销毁了此返回对象。然后operator=()函数将副本复制到motto3中。最后,通过调用析构函数,销毁作为赋值操作右操作数的临时对象。这条语句导致了两个复制临时对象(rvalue)的操作。

我们感兴趣的第二条语句是:

  1. motto3motto3 = motto3 + motto1 + motto2; 

首先调用operator+()函数连接motto3和motto1,此运算符函数调用构造函数来创建要返回的对象。然后使用复制构造函数来复制返回的对象,在析构函数销毁函数中创建的原始对象之后,通过再一次调用operator+()函数,连接副本与motto2,重复执行函数调用序列。最后,调用operator=()函数来存储结果。因此对于这条简单的语句,有3个临时对象复制操作,两个操作来自复制构造函数调用,一个操作来自赋值运算符。

如果CMessage是一个十分复杂的大对象,那么所有这些复制操作在运行时间方面是非常昂贵的。如果可以避免这些复制操作,就可以大大地提高执行效率。我们来看看如何能够做到这一点。

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇8.5.1 避免不必要的复制操作(1) 下一篇3.2.1 循环的概念(1)

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容:

·用 C 语言或者限制使 (2025-12-25 08:50:05)
·C++构造shared_ptr为 (2025-12-25 08:50:01)
·既然引用计数在做 GC (2025-12-25 08:49:59)
·Java 编程和 c 语言 (2025-12-25 08:19:48)
·. net内存管理宝典这 (2025-12-25 08:19:46)