• We refer to traditional C++ references (the single-ampersand one) as lvalue references. Modern C++ has introduced a new type called rvalue reference, denoted by placing a double ampersand && after some type. Such rvalue reference lets you modify the value of a temporary object. Rvalue references pave the way for the implementation of move semantics, a technique which can significantly increase the performance of your applications.
• Copy constructor/assignment is called when there’s an lvalue in input, while move constructor/assignment is called when there’s an rvalue in input.
I've got two questions:
1- Is the code fine to you too?
2- On line 103 myVec v4 = myVec(10);, we have a temp object myVec(10), then why isn't the move constructor called, please?
C++ compilers usually do something called "copy elision." In C++17, this is guaranteed, but compilers implemented it before that as well. What this basically means is that, in line 103, a copy/move is not considered and the object v4 is directly constructed with the temporary using the regular constructor. This is an optimization because now you don't call the regular constructor (to construct the temporary) followed by the move constructor (to construct the moved-into object with the temporary), you can instead just call the regular constructor to create the object instead of creating a temporary only to move it.
In gcc (if you are compiling with a standard lower than C++17), you can control copy elision with the compiler flag -fno-elide-constructors.
You can force the move constructor to be called by explicitly calling std::move
Yes. I got it, thank you. Copy elision eliminates calling the copy constructor when the object (used to copy from) is temporary, and the ordinary constructor will then be called to directly create the new object, as you said, right? So for a snippet like:
On line 9, the move assignment is called because v3 has previously been created.
I also read about return value optimization on the Web. But I think we just must tune these optimizations out and focus on designing our classes correctly to do their job properly and also let the compiler do its job properly as well (in needed).
But except for using std::move(), will you offer a snippet in which the move constructor is called, please.
I also read about return value optimization on the Web. But I think we just must tune these optimizations out and focus on designing our classes correctly to do their job properly and also let the compiler do its job properly as well (in needed).
Return value optimization is the same thing as copy elision, except it is a special type of copy elision that applies to return values of a function.
But except for using std::move(), will you offer a snippet in which the move constructor is called, please.