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
CodePudding user response:
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.