How to return && object from function? [duplicate]
Asked Answered
W

1

8

I have TTempTable class with move symantics. I wrote

TTempTable&& MyFunction() {
   TTempTable tmp = f(...);
   ...
   return std::move(tmp);
}

and got no compiler errors.

Was this correct?

Wolsky answered 27/5, 2019 at 12:53 Comment(1)
Have a look at this rule in the C++ Core GuidelinesArguelles
R
21

No, it is not correct.

You're returning a reference to a local variable. That reference is dangling.

Like any dangling thing, the compiler won't [always] diagnose it for you.

Return by value, and remove the std::move (it's redundant and inhibits elision).

Reinareinald answered 27/5, 2019 at 12:56 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.