Move constructor, move assignment c++ | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Move constructor, move assignment c++

I'm practicing about how move constructor and move assignment works, but I have a problem, somehow, lines 77-80 aren't executed, because of that, it won't show them in the console. But if I delete/comment lines 73-75. now the lines 77-80 can be shown in the console, why is that? lines 73-75 do std::move, which executes the move constructor from the class CString, did I do something wrong in my move constructor? or I used in a wrong way std::move ? Here is the code (which you can run it): https://code.sololearn.com/c6a24A18A044 Just comment lines 73-75 and now the lines 77-80 are executed.

16th Feb 2021, 6:06 AM
Eduardo Perez Regin
Eduardo Perez Regin - avatar
3 Answers
+ 2
Your class is fine, and actually the entire code is executed, the problem is that the moved-from object will return a nullptr when converted to const char*, which is undefined behaviour when trying to write from it into the output stream (see overload [2], last line): https://en.cppreference.com/w/cpp/io/basic_ostream/operator_ltlt2 It seems GCC reacts by setting the output error flags std::failbit and std::badbit, which, I think, will block the output stream until handled (you could manually clear the flags via std::cout.clear() afterwards to see the rest of the output). To resolve this, I'd say it would be best to overload the insertion operator << instead of relying on the conversion operator, as checking for a nullptr and returning something else during the conversion might be undesirable in another context (note nullptr != "", which you used in your constructor), although I guess it doesn't matter too much for simpler codes.
16th Feb 2021, 9:25 AM
Shadow
Shadow - avatar
+ 1
Eduardo Perez Regin Well, inserting "" into the output stream would be the same as inserting nothing, so maybe if ( cs.cstring != nullptr ) { os << cs.cstring; } return os; would be sufficient as a definition. Other than that, I don't think you can improve on it. It's a fairly simple function for a string wrapper, after all.
17th Feb 2021, 11:52 AM
Shadow
Shadow - avatar
0
Shadow I never thought that trying to use std::cout with nullptr could give some undefined behavior, that shows that I need to read documentation :) Thank you for your answer, I overloaded the << operator and now it works fine. The solution I implemented I think is not the best but it works, is there another way to improve this solution? friend ostream& operator << (ostream& os, const CString & cs) { If(cs.cstring == nullptr) os << ""; else os << cs.cstring; return os; }
16th Feb 2021, 6:38 PM
Eduardo Perez Regin
Eduardo Perez Regin - avatar