简体   繁体   中英

How to properly bind rvalues to the constructor?

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.

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

test m{ dummy{} };

which declares a variable m passing a temporary dummy .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM