mardi 3 novembre 2020

Is it reasonable approach when C++ function does not 'move from' rvalue reference argument?

Suppose the class Object satisfies the requirements of MoveConstructible and MoveAssignable, but not the requirements of either CopyConstructible or CopyAssignable (i.e. PIMPL with unique_ptr within). Then I have two consumers:

 bool consumer1(Object && arg) {
       if(arg ...) { // arg satisfies some condition
          Object b {std::move(arg)};
          // some processing
          return true;
        }
        return false;
 }

 bool consumer2(Object &&arg) {};

 int main() {
     Object arg;
     // some arg initialization here
     if(!consumer1(std::move(arg))) 
        consumer2(std::move(arg));
 }

i.e. I want to move an instance of Object to consumer1() and if it does not accept it for some reason I move the instance to consumer2().

Alternatively, I could check the state of the instance (i.e. whether it was move from or not) instead of relying of the return value.

While I know that

std::move doesn’t move anything.

I nevertheless feel uncomfortable due to two moves.

Is it a reasonable approach? Is there a less convoluted way to implement the same idea?

Aucun commentaire:

Enregistrer un commentaire