在 getter 中 return 字符串引用的正确方法
Correct way to return string reference in getter
我有一个带有字符串属性的 class,我的 getter 必须 return 字符串和这些属性的值。
我设法做到没有错误的唯一方法是这样的:
inline string& Class::getStringAttribute() const{
static string dup = stringAttribute;
return dup;
}
在 C++ 中编写 getter return 私有字符串属性的字符串引用的正确方法是什么?
这样做:
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
。因此,对象内部的任何状态都不能改变。如果您 return 一个成员变量(在本例中为 stringAttribute)的别名,您将允许更改对象内部的状态(对象外部的代码可以更改字符串)。
有两种可能的解决方案:要么简单地 return 一个 string
,其中实际上将 returned 一个 stringAttribute 的副本(因此对象的状态仍然是相同) 或 return 一个 const 字符串,其中调用该方法的任何人都不能更改 stringAttribute 的值。
此外,您可以从 getStringAttribute() 中删除 const
,但这样任何人都可以更改 stringAttribute 的值,您可能想要也可能不想要。
return 副本或 const 引用:
std::string get() const { return s_; }
const std::string& get() const { return s_; }
我有一个带有字符串属性的 class,我的 getter 必须 return 字符串和这些属性的值。
我设法做到没有错误的唯一方法是这样的:
inline string& Class::getStringAttribute() const{
static string dup = stringAttribute;
return dup;
}
在 C++ 中编写 getter return 私有字符串属性的字符串引用的正确方法是什么?
这样做:
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
。因此,对象内部的任何状态都不能改变。如果您 return 一个成员变量(在本例中为 stringAttribute)的别名,您将允许更改对象内部的状态(对象外部的代码可以更改字符串)。
有两种可能的解决方案:要么简单地 return 一个 string
,其中实际上将 returned 一个 stringAttribute 的副本(因此对象的状态仍然是相同) 或 return 一个 const 字符串,其中调用该方法的任何人都不能更改 stringAttribute 的值。
此外,您可以从 getStringAttribute() 中删除 const
,但这样任何人都可以更改 stringAttribute 的值,您可能想要也可能不想要。
return 副本或 const 引用:
std::string get() const { return s_; }
const std::string& get() const { return s_; }