通过引用传递 r 值?
Passing r values by reference?
我经常编写通过非常量引用获取参数的函数,但缺点是我无法传递右值。
我的一位同事向我展示了这段据说可以解决问题的代码:
#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;
}
这个未定义的行为是因为悬空引用吗? (在调用 f
之前 5
会被销毁吗?)
临时文件什么时候销毁?
当完整的表达式完成时,临时对象被销毁(除了一些例外)。
所以你在这里很好。
关于 lifetime 的更多详细信息:
All temporary objects are destroyed as the last step in evaluating the full-expression that (lexically) contains the point where they were created, and if multiple temporary objects were created, they are destroyed in the order opposite to the order of creation. This is true even if that evaluation ends in throwing an exception.
There are two exceptions from that:
- The lifetime of a temporary object may be extended by binding to a const lvalue reference or to an rvalue reference (since C++11), see reference initialization for details.
- The lifetime of a temporary object created when evaluating the default arguments of a default or copy constructor used to initialize an element of an array ends before the next element of the array begins initialization.
我经常编写通过非常量引用获取参数的函数,但缺点是我无法传递右值。
我的一位同事向我展示了这段据说可以解决问题的代码:
#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;
}
这个未定义的行为是因为悬空引用吗? (在调用 f
之前 5
会被销毁吗?)
临时文件什么时候销毁?
当完整的表达式完成时,临时对象被销毁(除了一些例外)。 所以你在这里很好。
关于 lifetime 的更多详细信息:
All temporary objects are destroyed as the last step in evaluating the full-expression that (lexically) contains the point where they were created, and if multiple temporary objects were created, they are destroyed in the order opposite to the order of creation. This is true even if that evaluation ends in throwing an exception.
There are two exceptions from that:
- The lifetime of a temporary object may be extended by binding to a const lvalue reference or to an rvalue reference (since C++11), see reference initialization for details.
- The lifetime of a temporary object created when evaluating the default arguments of a default or copy constructor used to initialize an element of an array ends before the next element of the array begins initialization.