Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In C++, I want my interface, .h to say int GetSomeInt() const;.... but actually the method *DOES* update "this".

Tags:

c++

constants

I'm adding some lazy initialization logic to a const method, which makes the method in fact not const. Is there a way for me to do this without having to remove the "const" from the public interface?

int MyClass::GetSomeInt() const
{
    // lazy logic
    if (m_bFirstTime)
    {
        m_bFirstTime = false;
        Do something once
    }

    return some int...

}

EDIT: Does the "mutable" keyword play a role here?

like image 917
Corey Trager Avatar asked Nov 29 '22 05:11

Corey Trager


1 Answers

Actually, you said that you didn't want to change the header file. So your only option is to cast away the constness of the this pointer...

int MyClass::GetSomeInt() const
{
    MyClass* that = const_cast<MyClass*>(this);

    // lazy logic
    if (that->m_bFirstTime)
    {
        that->m_bFirstTime = false;
        Do something once
    }

    return some int...

}

If using mutable raises a red flag, this launches a red flag store in to orbit. Doing stuff like this is usually a really bad idea.

like image 145
John Dibling Avatar answered Nov 30 '22 20:11

John Dibling