lundi 24 mai 2021

How to use overloaded function with rvalue and lvalue references

Hi i am trying to understand how to use overloaded versions of a function with rvalue and lvalue references as parameters. So this is the example i am writing to better understand the difference:

car.h

class Car{
    private:
      int number=1000;
      string name="default name";
      std::set<int> Carset;
    public:
       void pushtoset(int &);
       void pushtoset(int &&);

}

car.cpp

#include "car.h"

void Car::pushtocar(int &x){

    Carset.insert(x);
}
void Car::pushtocar(int &&x){
    Carset.insert(x);    
}

main.cpp

int main(){
    Car object;
    int x = 43;    
object.pushtocar(x); //this calls pushtocar(int&) version(say version I)
object.pushtocar(54); // this calls pushtocar(int &&) version(say version II)
    return 0;

My question is in the case of version II when this member function's body is completed and since inside the function body the parameter x is an lvalue(which is local to the function), x will be destroyed. Does this mean that the value that we have inserted in the set will also be destroyed? If so how can i prevent the value that is pushed onto the set to not be destroyed? My second question which i think is related to the first is that when i write Carset.insert(x); in the version II will x be copied or moved? I think it will be copied. And so if x is copied then there is no problem if x is destroyed because the inserted element and x are independent of each other. But now instead if i write Carset.insert(std::move(x)); then x will be "moved" to the set instead of copied. So in this case we will have the problem the after the function body completes, x will be destroyed and so the element inserted will also be destroyed. Is there any way to prevent the element inserted in the set in this moved case that is leave x in a valid state to be destroyed? Also is my understanding of the concept correct?

Aucun commentaire:

Enregistrer un commentaire