QScopedPointer
QScopedpointer
detailed description
the QScopedpointer class stores a pointer to a dynamically allocated object, and deletes it upon destruction.
managing heap allocated objects manually is hard and error prone, with the common result that code leaks memory and is hard to maintain. QScopedpointer is a small utility class that heavily simplifies this by assigning stack-based memory ownership to heap allocations, more generally called resource acquisition is initialization(raii).
QScopedpointer guarantees that the object pointed to will get deleted when the current scope disappears.
consider this function which does heap allocations, and has various exit points:
void myfunction(bool usesubclass)
{
myclass *p = usesubclass ? new myclass() : new mysubclass;
qiodevice *device = handsoverownership();
if (m_value > 3) {
delete p;
delete device;
return;
}
try {
process(device);
}
catch (...) {
delete p;
delete device;
throw;
}
delete p;
delete device;
}
it's encumbered by the manual delete calls. with QScopedpointer, the code can be simplified to:
void myfunction(bool usesubclass)
{
// assuming that myclass has a virtual destructor
QScopedpointer<myclass> p(usesubclass ? new myclass() : new mysubclass);
QScopedpointer<qiodevice> device(handsoverownership());
if (m_value > 3)
return;
process(device);
}
the code the compiler generates for QScopedpointer is the same as when writing it manually. code that makes use of delete are candidates for QScopedpointer usage (and if not, possibly another type of smart pointer such as QSharedPointer). QScopedpointer intentionally has no copy constructor or assignment operator, such that ownership and lifetime is clearly communicated.
The const qualification on a regular C++ pointer can also be expressed with a QScopedpointer:
const QWidget *const p = new QWidget();
// is equivalent to:
const QScopedpointer<const QWidget> p(new QWidget());
QWidget *const p = new QWidget();
// is equivalent to:
const QScopedpointer<QWidget> p(new QWidget());
const QWidget *p = new QWidget();
// is equivalent to:
QScopedpointer<const QWidget> p(new QWidget());
Custom Cleanup Handlers
Arrays as well as pointers that have been allocated with malloc must not be deleted using delete. QScopedpointer's second template parameter can be used for custom cleanup handlers.
The following custom cleanup handlers exist:
- QScopedpointerDeleter - the default, deletes the pointer using delete
- QScopedpointerArrayDeleter - deletes the pointer using delete []. Use this handler for pointers that were allocated with new [].
- QScopedpointerPodDeleter - deletes the pointer using free(). Use this handler for pointers that were allocated with malloc().
- QScopedpointerDeleteLater - deletes a pointer by calling deleteLater() on it. Use this handler for pointers to QObject's that are actively participating in a QEventLoop.
You can pass your own classes as handlers, provided that they have a public static function void cleanup(T *pointer).
// this QScopedpointer deletes its data using the delete[] operator:
QScopedpointer<int, QScopedpointerArrayDeleter<int> > arrayPointer(new int[42]);
// this QScopedpointer frees its data using free():
QScopedpointer<int, QScopedpointerPodDeleter> podPointer(reinterpret_cast<int *>(malloc(42)));
// this struct calls "myCustomDeallocator" to delete the pointer
struct ScopedPointerCustomDeleter
{
static inline void cleanup(MyCustomClass *pointer)
{
myCustomDeallocator(pointer);
}
};
// QScopedpointer using a custom deleter:
QScopedpointer<MyCustomClass, ScopedPointerCustomDeleter> customPointer(new MyCustomClass);
Forward Declared Pointers
Classes that are forward declared can be used within QScopedpointer, as long as the destructor of the forward declared class is available whenever a QScopedpointer needs to clean up.
Concretely, this means that all classes containing a QScopedpointer that points to a forward declared class must have non-inline constructors, destructors and assignment operators:
class MyPrivateClass; // forward declare MyPrivateClass
class MyClass
{
private:
QScopedpointer<MyPrivateClass> privatePtr; // QScopedpointer to forward declared class
public:
MyClass(); // OK
inline ~MyClass() {} // VIOLATION - Destructor must not be inline
private:
Q_DISABLE_COPY(MyClass) // OK - copy constructor and assignment operators
// are now disabled, so the compiler won't implicitely
// generate them.
};
Otherwise, the compiler output a warning about not being able to destruct MyPrivateClass.
Related Classed
- QSharedPointer.
QScopedPointer的更多相关文章
- Qt也有垃圾回收(通过QScopedPointer实现),下决心在项目里使用QScopedPointer,省了太多事情了,而且更安全!!
也谈Qt的垃圾回收 前几天在做代码审核的时候,Kai Uwe Broulik建议使用QScopedPointer来替代手工内存管理,使用后发觉确实节约了不少代码量,我的CHERRY可以延长寿命了!但是 ...
- Qt智能指针QPointer, QSharedDataPointer ,QSharedPointer,QWeakPointer和QScopedPointer
QPointer (4.0) 已经过时,可以被QWeakPointer所替代,它不是线程安全的. QSharedDataPointer (4.0) -- 提供对数据的COPY-ON-WRITE以及浅拷 ...
- QPointer更安全,QScopedPointer自动出范围就删除,QSharedDataPointer帮助实现隐式共享
http://blog.csdn.net/hai200501019/article/details/8474582http://blog.csdn.net/hai200501019/article/d ...
- Qt on Android 核心编程
Qt on Android 核心编程(最好看的Qt编程书!CSDN博主foruok倾力奉献!) 安晓辉 著 ISBN 978-7-121-24457-5 2015年1月出版 定价:65.00元 4 ...
- Qt 之 入门例程 (一)
以 “Hello Qt” 为例,介绍如何建立一个 Qt 工程 . 1 QLabel 例程 QLabel 继承自 QFrame (继承自 QWidget),主要用来显示文本和图片. 1.1 Hell ...
- Qt QObject
[1]Qt的QObject 1.测试代码如下: #include<QApplication> #include<QPushButton> #include<QDebug& ...
- QCustomplot使用分享(七) 层(完结)
一.分层绘制 一直说要讲2.0.0版本,但总是想把1.3.2版本拿出来比较一下,这篇文章也不例外.QCustomPlot2.0.0beta版本比1.3.2release版本有一个很大的改进那就是分层绘 ...
- QCustomplot使用分享(六) 坐标轴和网格线
一.概述 前边已经写了5篇对QCustomPlot的讲解,看过上述的几篇文章后,基本就能做一些简单的使用了,但是如果想要做到高度的控制图表,那么坐标轴将是很重要的一部分,因为坐标轴就是图表的一个参考系 ...
- Qt中单例模式的实现(4种方法)
最简单的写法: 12345 static MyClass* MyClass::Instance(){ static MyClass inst; return &inst;} 过去很长一段时间一 ...
随机推荐
- 队列模拟题——pat1026. Table Tennis
题意自己理解了,主要是两个队列维护,一个VIP队列,一个普通队列 搜集了一些坑(有些坑转自别的网站用于广大同学的测试之用) 普通人也有VIP的权益!!! 屌丝逆袭有木有!!! 920:52:00 10 ...
- Makefile编写 五 隐含规则
隐含规则———— 在我们使用Makefile时,有一些我们会经常使用,而且使用频率非常高的东西,比如,我们编译C/C++的源程序为中间目标文件(Unix下是[.o]文件,Windows下是[.obj] ...
- 机器学习之代价函数(cost function)
代价函数(有的地方也叫损失函数,Loss Function)在机器学习中的每一种算法中都很重要,因为训练模型的过程就是优化代价函数的过程,代价函数对每个参数的偏导数就是梯度下降中提到的梯度,防止过拟合 ...
- 实现 Win32 程序的消息映射宏(类似 MFC )
对于消息映射宏,不用多说了,用过 MFC 的人都很清楚.但目前有不少程序由于各种原因并没有使用 MFC,所以本帖讨论一下如何在 Win32 程序中实现类似MFC的消息映射宏.其实 Windows 的头 ...
- m'ybatis 一对一 一对多 配置详解
javabean: package com.me.model; import java.io.Serializable; import java.util.Date; import java.util ...
- SPUtils
public class SPUtils { /** * 保存在手机里的SP文件名 */ public static final String FILE_NAME = "my_sp" ...
- Hibernate学习11——配置Hibernate二级缓存
一.缓存的概念: 以空间换时间: 二.Hibernate缓存的分类: 前面我们讲的缓存都是session缓存:也叫一级缓存:get,load等缓存都是内置的,一级缓存: SessionFactor ...
- Eclipse中设置JDK、${user}变量
为eclipse设置jdk方法: 两个方法: 1.设置PATH路径-eclipse自动会查找! 2.在快捷方式中加上参数:-VM java虚拟机路径 Eclipse中设置${user}变量 在Ecli ...
- IT运维的定义
IT运维是IT管理的核心和重点部分,也是内容最多.最繁杂的部分,该阶段主要用于IT部门内部日常运营管理,涉及的对象分成两大部分,即IT业务系统和运维人员,该阶段的管理内容又可细分为七个子系统: ...
- zookeeper基本讲解(Java版,真心不错)
1. 概述 Zookeeper是Hadoop的一个子项目,它是分布式系统中的协调系统,可提供的服务主要有:配置服务.名字服务.分布式同步.组服务等. 它有如下的一些特点: 简单 Zookeeper的核 ...