Quantcast
Channel: Jobs
Viewing all articles
Browse latest Browse all 18427

[Solved] creating new Object in const method

$
0
0
Ok, I admit, from the title alone, it sounds like “oh no!”. But there’s good reason for my madness. The problem in a nutshell: Within a ‘const’ method, I create a new Object: m_pLayoutTextDocument = new QTextDocument(this); which has been declared as ‘mutable’ mutable QTextDocument* m_pLayoutTextDocument; Even though declared as mutable, gcc complains: error: invalid conversion from 'const QObject*' to 'QObject*' The reason why I am doing this at all is lazy initialization, a pattern I use regularly: The m_pLayoutTextDocument I create will, for many instances of my class, not be used at all. Since my object can be created often, and only some of them us the TextDocument (for calculation of preferred size, btw.), I want to delay the creation of this object until the last possible time. The last possible time (and a very logical one, too) is when the user of the class calls myclass.getPreferredSize(); which is a ‘const’ method (otherwise, the user of my class gets into trouble with his const correctness). So, within getPreferredSize(), I have     if ( ! m_bPreferredSizeValid )     {         updatePreferredSize();     }       return m_LastPreferredSize; so updatePreferredSize() must be ‘const’ too, and hence the problem. One possible solution would be to cast away my own const-ness in order to call a non-const method creating the object. Do you think that it would be safe (while undoubtedly ugly) to do the following: CTpeb_GraphicsTextPrivate* thisMutable = const_cast<CTpeb_GraphicsTextPrivate*>(this); // Now I can call a non-const method which creates my object thisMutable->createLayoutDocument();

Viewing all articles
Browse latest Browse all 18427

Trending Articles