Move constructor problem

If I dont include the move constructor(line 30) ,if I do include it --reference to local var temp returned(enabled by default
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
#include <iostream>
using namespace std;
class MyObj
{
public:
    MyObj()
        :varI(0),varD(0)
    {
    }

    MyObj(int MyObj,double b)
        :varI(MyObj),varD(b)
    {
    }
    void print()
    {
        cout<<"int:"<<varI<<" double:"<<varD<<endl;
    }
    MyObj& operator+(MyObj &o)
    {
        MyObj temp;
        temp.varI=varI;
        temp.varD=varD;
        temp.varI+=o.varI;
        temp.varD+=o.varD;
        return temp;
    }
    int getVarI()  {return varI;}
    int getVarD()  {return varD;}
    MyObj (MyObj && o)//MOve constructor
    {
        varI=o.varI;
        varD=o.varD;
    }
private:
    int varI;
    double varD;
};
ostream& operator<<(ostream& out,MyObj & o)
{
    out<<o.getVarI()<<" "
    <<o.getVarD()<<endl;
    return out;
}
int main()
{
    MyObj o1(3,33.33);
    MyObj o2(2,22.22);
    MyObj o3=o1+o2;    //reference to local var temp returned(enabled by default
    o3.print();
    MyObj o4;
    cout<<o4;
    MyObj  o5(move(o1));
}

Last edited on
When you declare a move constructor the implicitly defined copy constructor will be deleted.
There is no reason why you should define a move constructor for MyObj because it will do the same as the copy constructor anyway.
Thanks,I am learning C++ now ,and it was explained that if our object is big is better to use move instead of copy.
Can you explaine why implicitly defined copy constructor will be deleted
Lio wrote:
Can you explaine why implicitly defined copy constructor will be deleted

Because the standard says so

C++11 ยง12.8/7
If the class definition declares a move constructor or move assignment operator, the implicitly declared copy constructor is defined as deleted;

If there is a reason do define a move constructor the default copy constructor will almost certainly don't work. I guess that is the reason for this rule.
Thanks
I though,that I dont have copy constructor declare,could you point where is the copy constructor
You should get that reference to local var temp returned(enabled by default whether or not
you have the move contructor - because the operator+ function does return a reference to a local variable...

Lio wrote:
Thanks,I am learning C++ now ,and it was explained that if our object is big is better to use move instead of copy.

Who said that - or what book did you read that from??
That is totally incorrect!
Topic archived. No new replies allowed.