Please see the following code examples:
(A)
#include <iostream>
#include <utility>
struct wrapper {
int&& x;
};
void f(wrapper a) { std::cout << std::move(a.x) << std::endl; }
int g() { return 0; }
int main() {
f(wrapper{g()});
}
(B)
#include <iostream>
#include <utility>
struct wrapper {
int&& x;
};
wrapper make_wrapper(int&& x) {
return{ std::move(x) };
}
void f(wrapper a) { std::cout << std::move(a.x) << std::endl; }
int g() { return 0; }
int main() {
f(make_wrapper(g()));
}
Are these examples valid? That is, are temporaries created by g
alive until the execution of f
finishes? What happens when f
takes its argument as a reference?