[Qt-interest] What is the use of QWeakPointer
Dan Milburn
danmilburn at clara.co.uk
Fri Apr 9 12:02:02 CEST 2010
Matthias Pospiech wrote:
> I was trying to use QWeakPointer, but I do not see how to use it as a
> replacement for c++ pointers.
>
> First I can not contruct it with a QThread based class:
>
> checkPositionThread(new PiezoJenaControllerCheckPositionThread(this, this))
>
> with
>
> class PiezoJenaControllerCheckPositionThread : public QThread
> {
> Q_OBJECT
> ...
>
> gives the error:
> 1>.\include\matthias\PiezoJena\PiezoJenaController.cpp(28) : error
> C2664: 'QWeakPointer<T>::QWeakPointer(const QWeakPointer<T> &)':
> Konvertierung des Parameters 1 von
> 'PiezoJenaControllerCheckPositionThread *' in 'const QWeakPointer<T> &'
> nicht möglich
> 1> with
> 1> [
> 1> T=PiezoJenaControllerCheckPositionThread
> 1> ]
> 1> Ursache: Konvertierung von
> 'PiezoJenaControllerCheckPositionThread *' in 'const QWeakPointer<T>'
> nicht möglich
> 1> with
> 1> [
> 1> T=PiezoJenaControllerCheckPositionThread
> 1> ]
> 1> Quelltyp konnte von keinem Konstruktor angenommen werden, oder
> die Überladungsauflösung des Konstruktors ist mehrdeutig
>
> And further it has not -> Operator so that I can not access the pointer
> as if it was a normal pointer. This especially is a point that I do not
> understand.
> How shall I use a pointer class if I can not use the pointer in the way
> pointers are accessed normaly?
>
> Basically I have now switched back to c/c++ pointers until I understand
> how this smart pointer or any other smart pointer is supposed to be used.
> Maybe anyone can help me out with further information or an basic example?
Hi,
This is my understanding. QWeakPointer is not a 'regular' smart
pointer. It is not a replacement for normal C++ pointers. It holds a
weak reference to an object, that is it is used where it is expected
that the object can be deleted at any time. So adding operator -> would
be dangerous because you should not be using it without first checking
that the referenced object still exists.
The way I use it is as follows:
QWeakPointer<MyObject> weakPointer = ...
MyObject *o = weakPointer.data();
if( o )
{
// Do something with o
}
Obviously this would cause problems in a multi-threaded environment, but
then I don't think QWeakPointer is suitable for that.
As for your compile error, it's difficult to tell without a complete
example (and I do not understand the error message), but it looks like
you're probably trying to initialize the pointer in code that doesn't
know the complete type of PiezoJenaControllerCheckPositionThread,
otherwise the constructor that takes a QObject would work.
Dan
More information about the Qt-interest-old
mailing list