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?