Alb*_*ert 3 c++ rvalue-reference c++11
我正在研究右值引用,我对以下代码有疑问:
string func() {
return "Paul";
}
int main()
{
string&& nodanger = func();
// The lifetime of the temporary is extended
// to the life-time of the reference.
return 0;
}
Run Code Online (Sandbox Code Playgroud)
问题是:什么func()回归?
我相信这是发生的事情:
您的func()函数返回一个std::stringprvalue.该构造被用于构造std::stringIS
basic_string( const CharT* s,
const Allocator& alloc = Allocator() );
Run Code Online (Sandbox Code Playgroud)
此prvalue绑定到rvalue引用nodanger,该引用延长其生命周期以匹配引用本身的生命周期.参考折叠在这里没有发挥作用.
这与
string&普通参考有什么不同吗?
如果nodanger是a ,代码将无法编译,string&因为您无法将rvalues绑定到非const左值引用.示例中的生命周期扩展行为与以下情况相同
std::string const& nodanger = func();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
198 次 |
| 最近记录: |