正在更改const方法中的对象状态

Changing object state in const method

本文关键字:对象 状态 方法 const      更新时间:2023-10-16

我有一个类似的类:

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方法修改该成员。

检查用于声明tmpmutable关键字。

如果您试图修改属性,您应该退出方法签名的const限定符:

std::字符串&doSomething(){…}

如果你不想修改它,并且你想确保该方法返回你等待接收的内容:

const std::string&doSomething()常量{…}

返回const引用是确保引用值不变的最佳方式。但是,由于第二个常量限定符(指定方法不应修改当前对象),在返回类型之前没有常量限定符也应该工作良好。

总之,我完全同意@juancopanza干杯