I am new to programming. Sorry for my bad english. I tried using rvalue as an initializer for initial objects. Thus, in accordance with the code, it will print out what the constructor used and the assignment operator are. But it turned out the object "what2" and "what3", which does not print anything. here is the code:
#include <iostream> using namespace std; class X{ public: int x; X()= default; X(int num):x{num}{} X(const X& y){ x = yx; std::cout << "copy constructor" << std::endl; std::cout << x << std::endl; } X& operator=(const X& d){ x = dx; std::cout << "copy assignment" << std::endl; return *this; } X(X&& y){ x = yx; std::cout << "move constructor" << std::endl; } X& operator=(X&& b){ x = bx; std::cout << "move assignment" << std::endl; return *this; } }; X operator +(const X& a,const X& b){ X tmp{}; tmp.x = ax +bx; return tmp; } int main(int argc, const char * argv[]) { X a{7} , b{11}; X what1; cout << "---------------" << endl; what1 = a+b; cout << "---------------" << endl; X what2{a+b}; cout << "---------------" << endl; X what3 = a+b; cout << "---------------" << endl; std::cout << what1.x << std::endl; std::cout << what2.x << std:: endl; std::cout <<what3.x << std::endl; return 0; }
output:
--------------- move assignment --------------- --------------- --------------- 18 18 18 Program ended with exit code: 0
only "what1" uses the assignment correctly. so how can i use rvalue to initialize an object? and using operator = to initialize the object? thank you very much.
source share