Qt:内存管理

   在c++中 我们创建的对象分为两种情况:1 在栈中创建的对象   2在堆中创建的对象。 

  第一中情况:是由编译器为我们管理,当离开作用域时候 编译器会析构对象。 第二种情况:需要自己管理  我们在每当new 一个对象就要有一个对应的delete  一般情况下 在构造函数或初始化列表中new对象 在析构函数中delete

    Qt是C++库,所以是遵守c++内存管理的原则,但是在内存释放时 在Qt中很少见delete  原因是Qt使用了一些机制,使得我们不要要手动delete对象。这些机制构成了Qt的半自动内存管理。这些机制大概有两种方法(个人目前所能了解到的)实现内存的自动释放。

                 方法1: Qt对象树机制  详细描述见参考文献1  适用范围:所以QObject及其派生类

                 方法2:设置 Qt::WA_DeleteOnClose 标志位(当close时会析构该对象)  使用范围:QWidget及其派生类

                          使用这些机制 可以让Qt帮我们管理内存的释放,但同样也会造成一些问题

#include <QApplication>
#include <QLabel>
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
QLabel label("Hello Qt!");
label.show();
label.setAttribute(Qt::WA_DeleteOnClose);
return app.exec();
}
 对象是在栈上分配的 如果通过标记位方式 关闭label时候会 delete对象  此时就会报错。

  在Qt中通过这些机制将delete 隐藏起来,所以一般不建议使用delete。如果想手动delete对象 Qt提供了deletelater函数 这是QObject的成员函数。

  Qt文档中关于deletelater介绍如下: 

Schedules this object for deletion.

The object will be deleted when control returns to the event loop. If the event loop is not running when this function is called (e.g. deleteLater() is called on an object before QCoreApplication::exec()), the object will be deleted once the event loop is started. If deleteLater() is called after the main event loop has stopped, the object will not be deleted. Since Qt 4.8, if deleteLater() is called on an object that lives in a thread with no running event loop, the object will be destroyed when the thread finishes.

Note that entering and leaving a new event loop (e.g., by opening a modal dialog) will not perform the deferred deletion; for the object to be deleted, the control must return to the event loop from which deleteLater() was called.
 可以看到 对象不是直接删除 二是投递一个删除消息到事件队列中,在事件队列中 删除消息之前的该对象的相关消息将继续被响应执行。

这种方法避免了因为对象删除而导致相关已投递出的消息不会被响应的问题



参考文献:

   1 Qt 对象树

    2  Qt: 从delete说起


                            

               

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值