简体   繁体   English

如何正确绑定rvalues到构造函数?

[英]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()); 使用test m(dummy());

Output: nothing 输出:没什么

using test t(std::move(dummy())); 使用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&& ? 如果参数type&&是否必须使用std::move and isn't dummy() considered as an rvalue so why do i need to use std::move ? 并且不是dummy()被认为是一个右值,为什么我需要使用std::move I am somehow confused about binding rvalues to rvalue references and i would like to need some clarification. 我在某种程度上混淆了将rvalues绑定到rvalue引用,我想要一些澄清。

test m(dummy()); declares a function called m . 声明一个名为m的函数。 You probably meant: 你可能意味着:

test m{ dummy{} };

which declares a variable m passing a temporary dummy . 它声明了一个传递临时dummy的变量m

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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