Object usage post move | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Object usage post move

I thought that once we use move on object , we should not use the object. Is this correct or am I mistaken? Refer code below : Why Ketan is printed by display method called from main function? Isn't it display empty string as object is moved ? https://code.sololearn.com/cIW2yj9sbdnU/?ref=app

23rd Feb 2022, 4:45 AM
Ketan Lalcheta
Ketan Lalcheta - avatar
2 Answers
+ 3
That entirely depends on how the move constructor and assignment operator are implemented. All C++ library objects leave their moved from objects in a valid but possibly inconsistent state. For example the vector move constructor states that it leaves the moved from object in an empty() state. Calling clear() would be fine. pop_back() might not be a good idea. Right now you are not moving anything. All std::move does is cast the type into type&& so that the correct function is selected by the compiler. Even if you did move, your move constructor/assignment op assign the old string an empty string which is a perfectly valid string state to keep working with. If for example you had a pointer in your class that always points to a valid resource, but implemented your move constructor to make it point to a nullptr instead, then it would not be a good idea to reuse that object as the functions would cause a crash. This would also mean that the object is now in an invalid state.
23rd Feb 2022, 8:53 AM
Dennis
Dennis - avatar
0
Thanks Dennis It is much more clear to me now.. I updated code and now understand that move constructor is called either we construct object from temp obj or moving already created obj by move... What I was trying was something different to call rvalue ref method Is my understanding correct now? I also got most of the point from your response except one. Could you please elaborate more on paragraph related to vector example ?
23rd Feb 2022, 4:33 PM
Ketan Lalcheta
Ketan Lalcheta - avatar