[Solved] creating new Object in const method

  • 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
    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 )

    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

  • Moderators

    The constructor of QTextDocument takes a QObject * as parent. You are passing "this" there, which is const in a a const method. So you could pass no parent to get around the problem, but then you will need to make sure the m_pLayoutTextDocument is going to be deleted yourself.

  • Hmmmm....since the object is private to my class and ownership is never going to move around, deleting it in my destructor should be pretty risk-free.

    Thanks, that sounds like a better solution.

  • Lifetime Qt Champion

    You can also use a "QScopedPointer":http://qt-project.org/doc/qt-4.8/qscopedpointer.html for that purpose

  • Even better, thanks! Seems like I'm still asleep after a long weekend. ;-)

  • Lifetime Qt Champion

    You're welcome !

    Don't forget to update the thread's title to solved so other forum users may know that a solution has been found

  • Right. I always forget that. I think a "Solved my issue" button next to a reply post would be great for that.

  • Yeah, the Q&A feature that has been on test for so long by now might be actually used...

Log in to reply