error while QSharedPointer<const T>::create()
Solved
General and Desktop
-
Is it "expected" for QSharedPointer<const T>::create() not to work? I get an error:
/usr/include/qt5/QtCore/qsharedpointer_impl.h:439:9: error: invalid conversion from ‘const void*’ to ‘void*’ [-fpermissive] new (result.data()) T(std::forward<Args>(arguments)...);
casting from nonconst shared pointer and constructor from raw const pointer work.
I got this for Qt5.7.0 and Qt5.10.0.
Here is a minimal example:
#include <QSharedPointer> struct A {}; int main(int argc, char *argv[]) { auto ca = QSharedPointer<const A>::create(); return 0; }
Here is one file (not minimal) example but with few working cases, 2 not working and a debug. Commented defines are for "not compiling" parts.
#include <QSharedPointer> #include <QDebug> #define FROM_PTR //#define CONST_CREATE #define FROM_RAW_PTR #define PERFECT_FORWARD_CREATE //#define PERFECT_FORWARD_CREATE_CONST #define BUILTIN_CAST class A { public: A() = default; A(int i) : _i{i} {} void foo() const { qDebug() << "const foo" << _i; } void foo() { qDebug() << "foo" << ++_i; } private: int _i{0}; }; using ASPtr = QSharedPointer<A>; using ASCPtr = QSharedPointer<const A>; int main(int argc, char *argv[]) { Q_UNUSED(argc) Q_UNUSED(argv) #ifdef FROM_PTR qDebug() << "FROM_PTR"; auto a1 = ASPtr::create(); a1->foo(); auto ca1 = static_cast<ASCPtr>(a1); ca1->foo(); qDebug() << "\n"; #endif // FROM_PTR #ifdef CONST_CREATE qDebug() << "CONST_CREATE"; auto ca2 = ASCPtr::create(); ca2->foo(); qDebug() << "\n"; #endif // CONST_CREATE #ifdef FROM_RAW_PTR qDebug() << "FROM_RAW_PTR"; auto ca3 = ASCPtr(new const A); ca3->foo(); qDebug() << "\n"; #endif // FROM_RAW_PTR #ifdef PERFECT_FORWARD_CREATE qDebug() << "PERFECT_FORWARD_CREATE"; auto a2 = ASPtr::create(10); a2->foo(); qDebug() << "\n"; #endif // PERFECT_FORWARD_CREATE #ifdef PERFECT_FORWARD_CREATE_CONST qDebug() << "PERFECT_FORWARD_CREATE_CONST"; auto ca4 = ASCPtr::create(20); ca4->foo(); qDebug() << "\n"; #endif // PERFECT_FORWARD_CREATE #ifdef BUILTIN_CAST qDebug() << "BUILTIN_CAST"; QSharedPointer<A> a3 = ASPtr::create(); a3->foo(); auto ca4 = a3.constCast<const A>(); ca4->foo(); qDebug() << "\n"; #endif // BUILTIN_CAST return 0; }
ed1. added (working) case with QSharedPointer<T>::staticCast<const T>() + added debug messages for cleaner output
ed2. added minimal example