标签:des style color os 使用 java io strong ar
1.让创建的对象自己 delete 自己的子对象(这里所说的子对象,是指对象的属性,而不是子类,以下类似);
2.让最后一个对象处理 delete;
3.不管内存。
// QPointer 表现类似普通指针 QObject *object = new QObject; QPointer<QObject> mypointer = object; // 当对象 delete 之后,QPointer 会有不同的表现 delete object; if(object == NULL) printf("1:clean pointer\n"); else printf("1:dangling pointer\n"); if(mypointer.isNull()) printf("2:clean pointer\n"); else printf("2:dangling pointer\n");
1:dangling pointer 2:clean pointer
// 创建实例 QObjectCleanupHandler *cleaner = new QObjectCleanupHandler; // 创建第一个按钮,并注册 QPushButton *w = new QPushButton("Remove Me"); cleaner->add(w); w->show(); QObject::connect(w, SIGNAL(clicked()), w, SLOT(deleteLater()));// 如果第一个按钮点击之后,删除自身 // 创建第二个按钮,注意,这个按钮没有任何动作 w = new QPushButton("Nothing"); cleaner->add(w); w->show(); // 创建第三个按钮,删除所有 w = new QPushButton("Remove All"); cleaner->add(w); QObject::connect(w, SIGNAL(clicked()), cleaner, SLOT(deleteLater())); w->show();
class CountedObject { public: CountedObject() { ctr=0; } void attach() { ctr++; } void detach() { ctr--; if(ctr <= 0) delete this; } private: int ctr; };
class CountedObject : public QObject { Q_OBJECT public: CountedObject() { ctr=0; } void attach(QObject *obj) { ctr++; connect(obj, SIGNAL(destroyed(QObject*)), SLOT(detach())); } public slots: void detach() { ctr--; if(ctr <= 0) delete this; } private: int ctr; };
class CountedObject : public QObject { public: CountedObject() { } void attach(QObject *obj) { // 检查所有者 if(obj == 0) return; // 检查是否已经添加过 if(owners.contains(obj)) return; // 注册 owners.append(obj); connect(obj, SIGNAL(destroyed(QObject*)), SLOT(detach(QObject*))); } public slots: void detach(QObject *obj) { // 删除 owners.removeAll(obj); // 如果最后一个对象也被 delete,删除自身 if(owners.size() == 0) delete this; } private: QList owners; };
标签:des style color os 使用 java io strong ar
原文地址:http://my.oschina.net/u/566875/blog/307996