PDA

View Full Version : Using qSharedPointerConstCast syntax



scoutycat
22nd June 2016, 20:48
I have a function,

const QVector<double> & getmData() {return mData;}

I need to pass the return of this function to another function:

processData(QSharedPointer<QVector<double> > data)

I see that there is a function qSharedPointerConstCast(const QSharedPointer<T> &other) that should help me get from const QVector<double> & to QSharedPointer<QVector<double> > , but damned if I can make it work!! Something like...


QSharedPointer<QVector<double> > rawData = qSharedPointerConstCast<QVector<double> >(getmData());

but of course this throws a compile error, " no matching function for call to 'qSharedPointerConstCast(const QVector<double>&)'
QSharedPointer<QVector<double> > rawData = qSharedPointerConstCast<QVector<double> >(getmData());"


QSharedPointer<QVector<double> > rawData = qSharedPointerConstCast<QSharedPointer<QVector<double> >>(iter->second->getmData());
gives a no matching function error

^

jefftee
23rd June 2016, 05:14
There may be a more desirable way to accomplish this, but here's *one* way... First, a couple of typedefs to improve readability IMHO:



typedef QVector<double> DoubleVector;
typedef QSharedPointer<DoubleVector> SharedDoubleVectorPtr;


Then the following code:



DoubleVector dv = getmData();
SharedDoubleVectorPtr sp(&dv);


Hope that helps.

anda_skoa
23rd June 2016, 09:16
I see that there is a function qSharedPointerConstCast(const QSharedPointer<T> &other) that should help me get from const QVector<double> & to QSharedPointer<QVector<double> >

How would that help you?

You don't have a "const QSharedPointer<T>&".
You don't even have a QSharedPointer.

As jefftee wrote, you need to create a shared pointer.
But jefftee's suggestion would make the shared pointer delete the vector it is pointing to but it hasn't been allocated on the heap.

So you either need to create a copy on the heap or pass a custom delete function that doesn't actually delete the pointer.

Cheers,
_

jefftee
23rd June 2016, 18:22
But jefftee's suggestion would make the shared pointer delete the vector it is pointing to but it hasn't been allocated on the heap.

@anda_skoa, agreed, my focus was on getting him past his syntax error and with the minimal code the OP provided, I made some (perhaps incorrect) assumptions about his actual code.