I am having difficulty understanding the movement of constructors in C ++. I created a simple class with a standard constructor, copy constructor, move constructor, and destructor. In addition, I defined a function with two overloads, one accepts a reference to this class, and one accepts an rvalue reference to this class. My test code is below.
#include <iostream>
class c {
public:
c() {
std::cout << "default constructor" << std::endl;
}
c(const c& s) {
std::cout << "copy constructor" << std::endl;
}
c(c&& s) {
std::cout << "move constructor" << std::endl;
}
~c() {
std::cout << "destructor" << std::endl;
}
};
void f(c& s) {
std::cout << "passed by reference" << std::endl;
}
void f(c&& s) {
std::cout << "passed by rvalue reference" << std::endl;
}
int main() {
c s1;
std::cout << "\n";
c s2(s1);
std::cout << "\n";
c s3(c());
std::cout << "\n";
f(s1);
std::cout << "\n";
f(c());
getchar();
return 0;
}
The output I get is not what I expected. Below is the output I get from this code.
default constructor
copy constructor
passed by reference
default constructor
passed by rvalue reference
destructor
, line 3. line 3, c s3(c());, c() r, , s3 . , . line 5 rvalue f(), , rvalue. .
: , c s3(std::move(c()));, rvalue s3? std::move?