To improve code readability, I want to create an object inside a function an return it by value (I let the compiler the task of optimizing the memory).
If I have a regular class I can do the following:
MyClass myFunction01()
{
MyClass theRegularObject;
//do things
return theRegularObject;
}
So in my code I can do:
MyClass myObject = myFunction01();
However, if MyClass is a QObject derived one (let's call it QObjDerivedClass), I get a compilation error:
QObjDerivedClass::QObjDerivedClass(const QObjDerivedClass &) : attempting to reference a deleted function.
I think that the problem resides in that the QObject has neither a copy constructor nor an assignment operator QObject Doc.
As possible solutions I think the following ones, but maybe I am missing a better one?
1.Create the object in main and pass the object as a reference to the function
void myFunction01(CMyClass &theObj) {//do things}
//In my program
CMyClass myObj;
myFunction01(myObj);
2.Create a dynamic object inside the function and return a pointer (a smart pointer?)
QSharedPointer<CMyClass> myFunction01()
{
QSharedPointer<CMyClass> p_theObj(new CMyClass);
//do things
return p_theObj;
}
//At my program
QSharedPointer<CMyClass> p_myObj = myFunction01();
//When p_myObj goes out of scope the CMyClass object will be deleted.
//WARNING: Very important not to set a parent when we create the CMyClass object.
//Otherwise, we will have problems due to double deletion.
Are there any better/other ideas?
QObjects. Please also check this: doc.qt.io/qt-5/objecttrees.html - KaneQObjectis neither copyable nor movable because otherQObjects refer it via its address, e.g. in parent-child relationship or in signals and slots. Check out this: bugreports.qt.io/browse/QTBUG-49604 - KaneQObjectsubclasses that aren't widgets, with the natural limitation that none of your code can hold on to the object via a naked pointer as such a pointer would become invalid.QPointerwould still work, of course. But since Qt itself only referencesQObjects internally in a few well known locations that the move constructor can fix up, it's possible to do it without patching Qt. I'll probably write up the solution I use at some point. It does the job.QWidgetis too convoluted to become a movable class without changing Qt itself. - Kuba hasn't forgotten Monica