// Example program #include <iostream> #include <string> void f(const int& x) { std::cout << "lvalue reference to const overload f(" << x << ")\n"; } void f(int&& x) { std::cout << "rvalue reference overload f(" << x << ")\n"; } #include <typeinfo> #include <string> int main() { f(3); int&& z = 3; f(z); } Why in this case, when f (z) is called, the const lvalue function is called, not the second, because the type z is an rvalue refference?
and the second question:
class A { public: A() { std::cout << "A constructor" << std::endl; } ~A() { std::cout << "A destructor" << std::endl; } A(const A& other) { std::cout << "A copy constructor" << std::endl; } A(A&& other) { std::cout << "A move constructor" << std::endl; } }; class B : public A { public: B() : A() { std::cout << "B constructor" << std::endl; } ~B() { std::cout << "B destructor" << std::endl; } B(const B& other) : A(other) { std::cout << "B copy constructor" << std::endl; } B(B&& other) : A(other) { std::cout << "B move constructor" << std::endl; } }; int main() { std::vector<B> v; std::cout << ">>> Pushing first element" << std::endl; v.push_back(B()); std::cout << ">>> First element was pushed" << std::endl; } Why in this case A copy constructor is called, but not A move constructor: how is it connected with lvalue and rvalue, and with overloading?
update:
changed the line as stated in the excellent answer:
B(B&& other) : A(std::move<B&>(other)) { Thanks to what the conclusion now looks like this:
>>> Pushing first element A constructor B constructor A move constructor B move constructor B destructor A destructor >>> First element was pushed >>> Pushing second element A constructor B constructor A move constructor B move constructor A copy constructor B copy constructor B destructor A destructor B destructor A destructor >>> Second element was pushed B destructor A destructor B destructor A destructor Updated question:
The last two copy ctor'a are called as far as I understand it when the magnitude of the vector increases and when they are copied (as I understand it, the implementation is through a dynamic array), if not the reason, correct it. How to make so that those places was called move ctor?
tried this:
v.push_back(std::move<B&&>)B()(); Changed nothing.
When these elements are already in the vector, as far as I understand, they are already lvalue.
The strangeness is that the task (the study of the behavior of rvalue and lvalue) says that you can additionally change somehow the same line that was mentioned above by some special specifier, which for the sake of such cases is added to c ++ 11, to call the move constructor in this case. Tell me how to do this?