正在更改const方法中的对象状态
Changing object state in const method
我有一个类似的类:
class A{
std::string tmp;
public:
const std::string &doSomething() const{
tmp = "something";
return tmp;
}
};
方法doSomething()
是const
并且返回引用而不是字符串本身是非常重要的。
我认为唯一的方法是使用动态分配,例如:
class A{
MyClass *tmp = new MyClass();
public:
const MyClass &doSomething() const{
*tmp = "something";
return *tmp;
}
};
tmp
变量"占位符"仅在doSomething()
内部使用。
有没有其他更清晰、更好的方法来存储这种临时值?
您可以在std::string tmp
:上使用mutable
修饰符
class A {
mutable std::string tmp;
...
}
这将允许const
方法修改该成员。
检查用于声明tmp
的mutable
关键字。
如果您试图修改属性,您应该退出方法签名的const限定符:
std::字符串&doSomething(){…}
如果你不想修改它,并且你想确保该方法返回你等待接收的内容:
const std::string&doSomething()常量{…}
返回const引用是确保引用值不变的最佳方式。但是,由于第二个常量限定符(指定方法不应修改当前对象),在返回类型之前没有常量限定符也应该工作良好。
总之,我完全同意@juancopanza干杯
相关文章:
- Constexpr替代了新的放置方式,可以让内存中的对象保持未初始化状态
- 在容器上移动分配:以前包含的对象的状态
- MATLAB:跟踪imufilter对象中的状态变化
- 是否很好地使用状态模式来维护当前选定的对象?
- "Extern"对象问题:错误:Id 返回 1 个退出状态
- 访问处于"移自"状态的对象
- 是 *this = Ctor();清除对象状态的合法和高效?
- 设计模式中对象中的过程(方法和操作)的状态
- 如何保持异步函数中使用成员的shared_ptr对象的活动状态?
- 无法访问/存储地图中的游戏状态对象
- 单元测试 - 设置私人成员以获得所需的对象状态
- 在不同的运行中保持对象状态
- 调用 ~Derived() 和 ~Base() 之间的对象状态
- 异常安全 - 用于可靠回滚对象状态的模式
- 从函数中更改对象状态
- 正在更改const方法中的对象状态
- c++中对象状态的重构
- C++RAII来管理对象状态的更改和恢复
- 从默认构造函数调用重载构造函数时,维护对象状态信息
- c++11中的线程安全对象状态操作