Chinaunix首页 | 论坛 | 博客
  • 博客访问: 139701
  • 博文数量: 124
  • 博客积分: 70
  • 博客等级: 民兵
  • 技术积分: 1745
  • 用 户 组: 普通用户
  • 注册时间: 2011-02-24 13:49
文章分类

全部博文(124)

文章存档

2011年(55)

2010年(14)

2009年(30)

2008年(25)

我的朋友

分类: WINDOWS

2011-04-27 19:37:58

qt 在heap 内存回收上扩展了一些能力,简单来说。

c++ 中内存的回收基本上分为几种方式

1. new & delete
2. 最后时刻delete
3. 不管,一般认为是泄露。(不排除有时候是故意的 )

但是qt 做的更好

1. qt 中对象以tree模式排列,即每个对象是一个节点,然后组合成一棵树,每个节点有一个parent,以及一个children。

2. 当一个对象的parent节点为非空时,即有父对象时候,可以不主动delete,而是依靠qt的自动回收机制,这个机制大致来说是,当一个对象子集为null时候,它会将children删除。

3. 当一个对象parent=null,即它是一个孤立节点时候,那么这类节点的内存回收需要依靠程序员自己管理。

这个机制你会发现时多么优雅啊,用它来处理ui对象再恰当不过了,因为大部分ui对象存在事实的tree关系,即有父窗口,子窗口,而且父窗口销毁时候恰恰也是子窗口销毁。



对象的创建于销毁机制

当对象是heap上创建的,那么qt能够保证每个对象仅仅被析构一次。

不过需要注意,qt并不保证析构顺序。


另外需要注意的是,stack上创建,析构对象有讲究。

 C++ language standard (ISO/IEC 14882:2003) specifies that destructors of local objects are called in the reverse order of their constructors. 

因此:

 int main()
 {
     QPushButton quit("Quit");
     QWidget window;

     quit.setParent(&window);
     ...
 }

In this case, the order of destruction causes a problem. The parent's destructor is called first because it was created last. It then calls the destructor of its child, quit, which is incorrect because quit is a local variable. When quit subsequently goes out of scope, its destructor is called again, this time correctly, but the damage has already been done.



最后需要说明一点,qt中内存还是要自己操心的。


1. 对象位于一个tree,那么你需要至少管理好它们的parent。

2. 对象是孤立的,那么和普通c++开发一样

3. 对象之间形成引用,且它们没有父子关系,这个时候需要考虑sharedptr等方式,否则qt并没有autorefcounting这种机制帮你管理。

http://saupb.blog.163.com/blog/static/47124178201102982357547/

http://hi.baidu.com/cccstudy/blog/item/54ded22869af9a3ed52af157.html


阅读(253) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~