0

On this thread (Should I return an rvalue reference parameter by rvalue reference?), it is written that The parameter cannot be a temporary (which is just what rvalue references represent). If I understand this sentence well, this code should not be correct

#include <string>
#include <iostream>
std::string &&f(std::string &&a) {
    return std::move(a);   
}

int main() {
    std::string a = f("lol");
    std::cout << a << std::endl;
    return 0;
}

However, when we look to std::get, it seems that it returns rvalue reference for temporary tuple, and I actually think that there is no issue with using std::get with temporary tuple.

So, I think I misunderstand the sentence above, and the prior code is correct. However, this one is not correct :

#include <string>
#include <iostream>
std::string &&f(std::string &&a) {
    return std::move(a);   
}

int main() {
    std::string &&a = f("lol");
    std::cout << a << std::endl;
    return 0;
}

It would be correct if the function returns a value and not rvalue reference. Am I correct?

Antoine Morrier
  • 3,930
  • 16
  • 37
  • 2
    The first code is correct because the temporary lasts until the end of the statement, and it is not accessed after that (`a` is constructed from it). The second code is UB because in `cout << a`, `a` refers to a temporary destroyed at the end of the first statement. It would be correct if `f` returned by value, since then the temporary that initializes `a` would be extended to match the lifetime of `a`. – M.M Nov 27 '18 at 23:10
  • 1
    There are infrequently times where this makes sense to do, but they are VERY few and far between. You virtually never want to do a `return std::move(...);` The only semi-common time I've ever found is when you build an object via rvalue-qualified methods: `MyType().set_prop(1).set_prop(2);` – xaxxon Nov 27 '18 at 23:33

0 Answers0