QSharedPointer与QMap混合使用的注意事项

来源:互联网 发布:软件系统架构 编辑:程序博客网 时间:2024/05/22 09:49

1.QSharedPointer内部的指针如果指向相同类型的相同对象,则操作符“==”返回true,可以看出QSharedPointer有对“==”操作符的重载。

Qt助手上解释如下:

bool operator==(const QSharedPointer<T> & ptr1, const QSharedPointer<X> & ptr2)
Returns true if the pointer referenced by ptr1 is the same pointer as that referenced by ptr2.

If ptr2's template parameter is different from ptr1's, QSharedPointer will attempt to perform an automatic static_cast to ensure that the pointers being compared are equal. If ptr2's template parameter is not a base or a derived type from ptr1's, you will get a compiler error.

2.QSharedPointer类没有对操作符“<”进行重载,因此QSharedPointer不能用作QMap的key。


3.QSharedPointer有拷贝构造函数的定义,在Qt助手中定义如下:

QSharedPointer::QSharedPointer(const QSharedPointer<T> & other)
Creates a QSharedPointer object that shares other's pointer.
If T is a derived type of the template parameter of this class, QSharedPointer will perform an automatic cast. Otherwise, you will get a compiler error.


4QSharedPointer有赋值操作符定义,在Qt助手中定义如下:

QSharedPointer<T> & QSharedPointer::operator=(const QSharedPointer<T> & other)
Makes this object share other's pointer. The current pointer reference is discarded and, if it was the last, the pointer will be deleted.
If T is a derived type of the template parameter of this class, QSharedPointer will perform an automatic cast. Otherwise, you will get a compiler error.


5.根据3与4可知,QSharedPointer类可以用于QMap中作为“值”对象的存储,这样可以变相保存用户自定义的对象指针而不用太关心内存释放的问题。


4.QOject 中没有提供一个拷贝构造函数和赋值操作符给外界使用,其实拷贝构造和赋值的操作都是已经声明了的,但是它们被使用了Q_DISABLE_COPY () 宏放在了private区域。因此所有继承自QObject的类都使用这个宏声明了他们的拷贝构造函数和赋值操作符为私有。

为什么要这样做?


我们都知道Qt对标准C++增加了一些功能:signals, slots, object properties, events, event filters, string translation, timers,object trees, guarded pointers, dynamic cast.

新加入的这些功能就要求我们把每一个QObject的对象看做是唯一(identities)的。唯一的意思就是不能通过拷贝或者赋值操作

制作出一个一模一样的复制体。

试想如果我们有一个QPushButton对象btnSubmit,如果我们可以复制出一个和btnSubmint完全一样的button对象,那么新的button对象的名字应该是什么?如果也叫btnSubmit,当我们给其中的btnSubmit接收事件或发出信号时,系统如何区分把事件由哪个button对象接收,或者哪个对象发送了信号?

 

我们知道在各种容器中能以value方式存放的类型,必须有默认的构造函数,拷贝构造函数和赋值操作。由于QObject及所有继承自它的子类都没有提供拷贝构造和赋值操作,当我们使用QList<QObject>时,编译器就会报错。如果我们要在容器中存储这中类型的对象,我们就要使用它们的指针。如QList<QObject *>

原创粉丝点击