vendredi 29 juin 2018

Move constructor comment not getting printed

I have a small program like below:

    class boovector{
    private: int size;
            char *arr;
    public:
            boovector(){size=1;arr=new char[size];cout<<" boovector default constructor called"<<endl;}
            boovector(const boovector &b)
            {
                cout<<"boovector copyconstructor called"<<endl;
                size = b.size;
                arr =  new char[size];
                strncpy(arr,b.arr,size);
            }
            boovector(boovector &&b)
            {
                cout<<"boovector move assignment operator called"<<endl;
                size =b.size;
                arr = b.arr;
                b.arr = nullptr;
            }
            ~boovector()
            {
                delete []arr;
            }

    };
    boovector createboovector()
    {
        boovector v;
        return v;
    }
    void foo(boovector v)
    {

    }
    int main(int argc, char *argv[])
    {
        boovector vet = createboovector();
        foo(vet);
        foo(createboovector());
        return 0;
    }

Output

boovector default constructor called
boovector copyconstructor called
boovector default constructor called

I was hoping to see "boovector move assignment operator called" in the output.

If I comment move constructor "boovector(boovector &&b)", i get compiler error

  invalid initialization of non-const reference of type 'boovector&' from an 
  rvalue of type 'boovector'

I want to understand the logic behind the move constructor not being called.

Aucun commentaire:

Enregistrer un commentaire