Som*_*mer 6 c++ language-lawyer c++20
我经常编写通过非常量引用获取参数的函数,但缺点是我无法传递 r 值。
我的一位同事向我展示了这段据说可以解决问题的代码:
#include <iostream>
// example function
int f(int& x) {
x += 5;
return x;
}
// is this undefined behaviour?
auto& to_l_value(auto&& x) {
return x;
}
int main () {
auto y = f(to_l_value(5)); // usage example
std::cout << y; // 10
return 0;
}
Run Code Online (Sandbox Code Playgroud)
这是由于悬空引用而导致的未定义行为吗?(5之前被摧毁了f在调用
临时的什么时候被销毁?
| 归档时间: |
|
| 查看次数: |
206 次 |
| 最近记录: |