正确的方法返回getter中的字符串参考

Correct way to return string reference in getter

本文关键字:字符串 getter 参考 返回 方法      更新时间:2023-10-16

我有一个带有字符串属性的类,我的获取器必须返回字符串&这些属性的值。

我设法完成此操作的唯一方法就是这样:

inline string& Class::getStringAttribute() const{
    static string dup = stringAttribute;
    return dup;
}

编写getter的正确方法是返回C 中私有字符串属性的字符串引用的正确方法?

这样做:

inline string& Class::getStringAttribute() const{
    return stringAttribute;
}

让我这个错误:

error: invalid initialization of reference of type ‘std::string& {aka std::basic_string<char>&}’ from expression of type ‘const string {aka const std::basic_string<char>}’

返回副本或const引用:

std::string get() const         { return s_; }
const std::string& get() const  { return s_; }

这里的问题是您将方法标记为const。因此,对象内部没有任何状态可以改变。如果将别名返回到成员变量(在这种情况下为StringAttribute),则允许对象内的状态更改(对象外部的代码可以更改字符串)。

有两种可能的解决方案:要么简单地返回一个string,其中实际上将返回StringAttribute的副本(因此该对象的状态保持不变),要么返回const字符串,其中称为该方法的人更改StringAttribute的值。

另外,您可以从getStringAttribute()中删除const,但是任何人都可以更改StringAttribute的值,您可能想要或可能不想要。