const to Non-const Conversion in C++

后端 未结 5 1430
鱼传尺愫
鱼传尺愫 2020-12-04 15:11

I\'m really annoyed by const keyword these days, as I\'m not quite familiar with it. I had a vector that stores all const pointers like vector

5条回答
  •  春和景丽
    2020-12-04 15:48

    void SomeClass::changeASettingAndCallAFunction() const {
        someSetting = 0; //Can't do this
        someFunctionThatUsesTheSetting();
    }
    

    Another solution is to call said function in-between making edits to variables that the const function uses. This idea was what solved my problem being as I was not inclined to change the signature of the function and had to use the "changeASettingAndCallAFunction" method as a mediator:

    When you call the function you can first make edits to the setting before the call, or (if you aren't inclined to mess with the invoking place) perhaps call the function where you need the change to the variable to be propagated (like in my case).

    void SomeClass::someFunctionThatUsesTheSetting() const {
         //We really don't want to touch this functions implementation
         ClassUsesSetting* classUsesSetting = ClassUsesSetting::PropagateAcrossClass(someSetting);
         /*
             Do important stuff
         */
    }
    
    void SomeClass::changeASettingAndCallAFunction() const {
         someFunctionThatUsesTheSetting();
         /*
             Have to do this
         */
    }
    
    void SomeClass::nonConstInvoker(){
        someSetting = 0;
        changeASettingAndCallAFunction();
    }
    

    Now, when some reference to "someFunctionThatUsesTheSetting" is invoked, it will invoke with the change to someSetting.

提交回复
热议问题