dimanche 23 août 2020

Confusion about object instance creation for temporary objects ( r values type )

Say for example I have a class as below. It has a copy constructor and move constructor defined in it.

class A
{
    public :
   
    int *ptr;
    
    A(int a)
    {
        cout<<"constructor called"<<endl;
        ptr = new int;
        *ptr = a;
    }
    
    ~A()
    {
        cout<<"destructor called"<<endl;
        delete ptr;
    }
    
    A(const A &a)
    {
        cout<<"copy constructor is called"<<endl;
        ptr = new int;
        *ptr = *(a.ptr);
    }
    
    A(A &&a) : ptr{a.ptr}
    {
        cout<<"Move constructor called"<<endl;
        a.ptr = nullptr;
    }
    
    void print() const
    {
        cout<<"val of data : "<<*ptr<<endl;
    }
};

a. When I just create a r valued reference and assign temporary to it :

int main(int argc, char** argv) {
    A &&y = A{20};
    return 0;
}

I get the output as below :

constructor called
destructor called

As per my understanding the constructor was called for the temporary object A{20} . And this was stored into the r valued reference.

b. When I just create an object and assign temporary to it ( with type cast ) :

int main(int argc, char** argv) {
    A y = (A &&)A{20};
    return 0;
}

I get the output as below :

constructor called
Move constructor called
destructor called
destructor called

As per my understanding the constructor was called for the temporary object A{20} . Move constructor was called for y.

c. When I create an object and assign temporary to it ( without type case ) :

int main(int argc, char** argv) {
    A y = A{20};
    return 0;
}

I get the output as below :

constructor called
destructor called

I expected that constructor would be called for A{20} and a move constructor or a copy constructor to be called for y. But it looks like the temporary object was not created here. Why is just a single object being created here ?

Aucun commentaire:

Enregistrer un commentaire