How to properly bind rvalues to the constructor?

55 views Asked by At

here is my code:

#include <iostream>


class dummy{
    public:
    //constructor + destructor
    dummy(){
    std::cout<<"dummy constructed"<<std::endl;
    }


    //copy 
    dummy(const dummy& o){
    std::cout<<"dummy copy init"<<std::endl;
    }


    void operator=(const&dummy){
    std::cout<<"dummy copy operator"<<std::endl;
    }

    //moves
    dummy(dummy&& other){
    std::cout<<"dummy move init"<<std::endl;        
    }

    void operator=(dummy&&){
    std::cout<<"dummy move copy"<<std::endl;
    }

};



class test{
    public:
    dummy d;

    test(dummy&& d):d(std::move(d)){
    std::cout<<"test"<<std::endl;   
    }
};




int main(int argc, char** argv) {

    test m(dummy());        //prints NOTHING.
    test t(std::move(dummy()));

    return 0;
}

using test m(dummy());

Output: nothing

using test t(std::move(dummy()));

Output:

dummy constructed
dummy move init
test

Which is something that is expected.

So my question is that,

Is it mandatory to use std::move if the parameter is type&&? and isn't dummy() considered as an rvalue so why do i need to use std::move ? I am somehow confused about binding rvalues to rvalue references and i would like to need some clarification.

1

There are 1 answers

2
M.M On BEST ANSWER

test m(dummy()); declares a function called m. You probably meant:

test m{ dummy{} };

which declares a variable m passing a temporary dummy.