简体   繁体   中英

Why userdefined move constructor is not called in below example?

I am expecting that after using std::move(any_object) we are converting that object in rvalue reference and due to this it should call my userdefined move constructor. but it is not working like this.Could anyone tell whats happening?

#include <iostream>
#include <memory>

struct Demo {
    int Value;
    Demo():Value(10) { std::cout << "Demo's default constructor called\n";}
    Demo(Demo& tempObj) { std::cout << "Demo non-const copy constructor called\n";}
    Demo(const Demo& tempObj) { std::cout << "Demo const copy constructor called\n"; }
    Demo(Demo&& tempObj) { std::cout << "Demo move constructor called\n"; }
    Demo(const Demo&& tempObj) { std::cout << "Demo const move constructor called\n"; }
    Demo& operator= (const Demo& tempObj){ std::cout << "Demo copy assignment operator called ";}
    Demo& operator= (Demo&& tempObj){ std::cout << "Demo move assignment operator called";}
    ~Demo(){ std::cout << "Demo's destructor called\n";}
};

void fun(Demo&& tempObj)
{
    tempObj.Value = 20;
}

int main()
{
    Demo demo;
    fun(std::move(demo));
}

//output:

Demo's default constructor called
Demo's destructor called

Why userdefined move constructor is not called in below example?

Because you're only binding an rvalue reference to an xvalue and not actually constructing an instance of type Demo . That is, a move constructor will be called when you actually construct an instance of type Demo using a rvalue as shown below for example:

//-----------v-------->removed && from here
void fun(Demo tempObj)
{
    tempObj.Value = 20;
}
fun(std::move(demo)); //now this uses move constructor

Additionally, you missing return statement in your assignement operators.

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