0
struct A{};

A test() {
  return A();
}

int main() {
  A a = test();
  A b = move(test());
  A c(move(test()));
}

Which method is better for "transferring" the value of test into my scope?

weineng
  • 146
  • 6
  • When you want something to be "best" (or even "better"), then you need some base-line to compare to. What is the goal of your program? What is the use-case? What is the original problem you need to solve? Oh and what is considered "best" could also be *very* subjective. – Some programmer dude Sep 07 '20 at 10:45
  • Apologies. I was thinking more of, what is the preferred way in c++ to "extract" the return value of `test()` into another method, to optimize for time and space (we don't create unnecessary temp object) complexity. – weineng Sep 07 '20 at 10:47
  • 1
    Names have scope, values don't. – molbdnilo Sep 07 '20 at 10:47
  • @molbdnilo Apologies, I should have said "result of test" instead of "value of test". – weineng Sep 07 '20 at 10:48
  • 1
    @weineng Those are the same thing. – molbdnilo Sep 07 '20 at 10:49
  • 1
    `std::move` turns its argument into an _rvalue_. Since `test()` call returns an rvalue by itself, using `std::move` for it is superfluous. Also note that there is no _assignment_ in your code, there is only _initialization_. – Daniel Langr Sep 07 '20 at 10:50
  • "Moving" doesn't actually move anything, and `std::move` is just a cast. The preferred way is to not do anything in particular – `A a = test();` will create the object in place, without any "extraction". – molbdnilo Sep 07 '20 at 11:01
  • @molbdnilo _will create the object in place, without any "extraction"_ — In C++11 (question tag), this is not guaranteed. However, it is very likely. – Daniel Langr Sep 07 '20 at 11:03

0 Answers0