copy ctor will copy a obj inside of function, So all theknowledge discussed in previous section can be used to helpyou understand copy ctor. A better method is overloadfunction to deal with lvalue and rvalue separately.
Typically, if you class allocate a lot of allocated resource (new, orvector, or sth else). You should implement two copy ctor A few
explanations are below:
Not move copy ctor will steal resource automatically, you need to
coding it by your self.
You can’t steal in normal ctor. because, It must keep origin obj
intact. You can steal when Foo(f1+f2), but when you used Foo(f1).
It will destory f1.
Without move copy ctor, normal copy ctor will treat Foo f = f1+f2
and Foo f = f1 the same way.
With move copy ctor, normal copy ctor deal with Foo f = f1, and
move deal with Foo f = f1+f2, for f1+f2, you can steal resource,
because nobody need to use f1+f2 later any more.
In move ctor, always set other.ptr = nullptr;
No const qualifier in move ctor and move assignment
In below examples, Foo obj1=obj2+obj3. if you don’t have move ctor, In
operator + function, a temp obj is produced, and when operator+ function
return, another temp obj temp2 is produced . Then in the end, objtemp2 is
passed to ctor, So, ctor is called three times. and copy content is also called
three times.
If you have move ctor. In operator + function, a temp objtemp1 is
produced, When return objtemp1, It will not produce objtemp2. (becasue
objtemp1 is rvalue.) then objtemp1 is passed to move ctor. In side move
ctor, the resource address has been move to new obj1. Just one temp
objtemp1 and one actual copy happen. ( just new pointer = old pointer; and
old pointer = NULL).
Move ctor and move assignment work with rvalue, What if you want to use
them with lvalues? You can call std::move function, It will call you
move ctor or assignment to "move" resource, not "copy" resource.