请考虑以下C++代码.
struct foo { std::string value; }
inline foo bar() { return { "42" }; }
Run Code Online (Sandbox Code Playgroud)
现在假设我有一个以下列方式使用bar()的函数.
std::string my_func()
{
const auto &x = bar();
return x.value;
}
Run Code Online (Sandbox Code Playgroud)
这是否泄漏内存因为my_func只保存对x的引用?或者,在my_func终止后,x仍然会被清除吗?
我知道这不是应该如何使用引用.但我刚刚意识到这个编译很好,并想知道它的语义是什么.
但我刚刚意识到这个编译很好
提供的代码不应该编译,因为尝试将临时分配给左值引用.
错误:从'foo'类型的右值开始无效初始化'foo&'类型的非const引用
如果您修改代码,请通过
std::string my_func()
{
const auto &x = bar();
return x.value;
}
Run Code Online (Sandbox Code Playgroud)
然后它会没问题,因为const引用延长了const引用生命周期的生命周期.
| 归档时间: |
|
| 查看次数: |
591 次 |
| 最近记录: |