假设我们需要一些类来包装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引用?
例如为:
inline operator const std::string &() const {
return m_value;
}
所以,上面的代码没有对临时复制工作吗?
PS:这个问题有点相关:Lifetime of temporaries,但仍然是一个不同的问题。
如果您有两个单独的问题,请创建两个单独的帖子。 –
关于与临时参考的const引用的生存期有关的问题Herb Sutter:http://herbsutter.com/2008/01/01/gotw-88-a-candidate-for-the-most-important-const/ –
@BenjaminLindley :是的,但是很难解释它的背景。所以,回答问题1的人可能也会回答问题2 :) – Frunsi