Changing object state in const method

2019-09-09 01:35发布

问题:

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