让我们假设我们需要一些包装std :: string的类,除了所有其他细节之外,它还使用类型转换操作符自动转换回std :: string:
class MyWrappedString {
std::string m_value;
/* ... */
public:
inline operator std::string() const {
return m_value;
}
};
因此,运算符将返回包装的字符串对象的副本。
但是,为什么以下代码看似正确?
MyWrappedString x;
const std::string& y = x;
// now, y should be a reference to a temporary, right?
std::cout << "y is: " << y << std::endl;
转换运算符将返回m_value的临时副本,因此const std::string& y = x
将创建对该临时副本的引用。
为什么这样做?我记得引用对象的生命周期有某种延伸,但我不确定。
第二个问题:是否可以使用返回const引用的类型转换操作符?
E.g:
inline operator const std::string &() const {
return m_value;
}
那么,上面的代码不必在临时副本上工作吗?
PS:这个问题与Lifetime of temporaries有点相关,但仍然是一个不同的问题。
答案 0 :(得分:2)
const
引用使引用保持活动状态(即使它通常超出范围),直到const引用超出范围
对于第二个问题:是的,你可以返回一个const引用,并且函数的返回值必须被赋予const引用