Changing object state in const method

你离开我真会死。 提交于 2020-01-07 03:10:50

问题


I have class that resembles this:

class A{
    std::string tmp;
public:
    const std::string &doSomething() const{
       tmp = "something";
       return tmp; 
    }
};

It is very important the method doSomething() to be const and to return reference instead of the string itself.

Only way I see is to do it with dynamic allocation, e.g. something like:

class A{
    MyClass *tmp = new MyClass();
public:
    const MyClass &doSomething() const{
       *tmp = "something";
       return *tmp; 
    }
};

tmp variable "placeholder" is used ONLY inside doSomething().

Is there some other, clear, better way to do this kind of temp value storage?


回答1:


You can use mutable modifier on std::string tmp:

class A {
  mutable std::string tmp;
  ...
}

This would allow a const method to modify that member.




回答2:


Check out the mutable keyword for declaring tmp.




回答3:


If you try to modify the attribute, you should quit the const qualifier of the method signature:

std::string& doSomething() { ... }

If you don't want to modify it, and you want to ensure that the method returns whatever you are waiting to receive:

const std::string& doSomething() const {...}

returning a const reference is the best way to ensure that the reference doesn't change of value. But without the const qualifier before the return type also should work well because of the second const qualifier (which specifies that the method shouldn't modify the current object)

In conclusion, I'm completely agree with @juanchopanza Cheers



来源:https://stackoverflow.com/questions/33596437/changing-object-state-in-const-method

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!