在const方法中更改对象状态 [英] Changing object state in const method
本文介绍了在const方法中更改对象状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有类似这样的类:
class A{
std::string tmp;
public:
const std::string &doSomething() const{
tmp = "something";
return tmp;
}
};
这是非常重要的方法 doSomething()
const
并返回引用而不是字符串本身。
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
变量placeholder里面 doSomething()
。
tmp
variable "placeholder" is used ONLY inside doSomething()
.
是否有其他一些更清楚,更好的方法来做这种类型的临时值?
Is there some other, clear, better way to do this kind of temp value storage?
推荐答案
您可以在 mutable
> std :: string tmp :
You can use mutable
modifier on std::string tmp
:
class A {
mutable std::string tmp;
...
}
这将允许 const
方法来修改该成员。
This would allow a const
method to modify that member.
这篇关于在const方法中更改对象状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文