【问题标题】:Correct way to return string reference in getter在getter中返回字符串引用的正确方法
【发布时间】:2017-09-16 18:12:11
【问题描述】:

我有一个带有字符串属性的类,我的 getter 必须为这些属性返回字符串和值。

我设法做到这一点而不会出错的唯一方法是这样的:

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

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

这样做:

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>}’

【问题讨论】:

  • 通常的方式是return stringAttribute;。如果您遇到错误,您需要在问题中包含错误消息的全文。
  • @PeteBecker 我试过了,但我遇到了这个错误:错误:从表达式中对类型“std::string& {aka std::basic_string&}”的引用无效初始化输入 'const string {aka const std::basic_string}'
  • 好昵称的法国人:D
  • 如果你想返回一个可修改的引用,你必须有一个非 const 访问器;从 const 访问器中,您只能返回对成员的 const 引用。你可以在这两种情况下返回一个 copy (返回一个普通的 string 对象),尽管如果调用者想要一个副本,如果你返回一个 const 引用,他总是可以自己制作一个。无论您做什么,都不要做您发布的内容 - 您正在返回一个对立即解除分配的字符串的引用 - 本质上是一个悬空引用。
  • 正如@MatteoItalia 指出的(我忽略了),这里的访问器函数标记为const,但它返回对非常量的引用;这两个不在一起。通常的做法是使用两个访问器:一个标记为const,返回const std::string&amp;,一个未标记const,返回std::string&amp;

标签: c++ syntax getter-setter


【解决方案1】:

返回一个副本或一个常量引用:

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

【讨论】:

  • 这篇文章两年了
  • 人们在寻找问题的答案时仍然会阅读这篇文章。我发布的原因是“官方”答案说返回一个“常量字符串”,这不是一个理想的答案。我正在为刚学习 C++ 的人澄清一下。
【解决方案2】:

这里的问题是您将方法标记为const。因此,对象内部的任何状态都不能改变。如果您将别名返回给成员变量(在本例中为 stringAttribute),您将允许更改对象内部的状态(对象外部的代码可以更改字符串)。

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

此外,您可以从 getStringAttribute() 中删除 const,但随后任何人都可以更改 stringAttribute 的值,您可能想要也可能不想要。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-08-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-04
    • 1970-01-01
    相关资源
    最近更新 更多