vendredi 5 juillet 2019

How to avoid unnecessary copying when whether the return type is a Rvalue or an Lvalue is decided at run time?

Consider the following line

const auto x = condition ? getLvalue() : getRvalue();

Because x is const, I don't need to copy the value returned by getLvalue, I would be happy if I could just take a reference to it. Of coure, the following would not compile

const auto& x = condition ? getLvalue() : getRvalue(); // Compilation error

as it makes no sense to make a reference to an R value.

How do I go around this problem? Is there problem or can I just trust the compiler to understand that the return type of getLvalue does not need copying?

Aucun commentaire:

Enregistrer un commentaire