So I’ve realised that a += b; is actually a = a + b;. (Try replacing a, b with strings.)
Is there a shortcut for a = b + a;? I’ve tried a =+ b; but that doesn’t seem to work.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
For std::string,
operator+=is an operator performed on the lhs argument that alters the argument and returns a reference. Sinceoperator+for strings means “append”, there is no possibility for you to have an such an operator for the other way round.This seems to be an annoying limitation at first, but actually there is a pretty good reason for that. std::string dynamically allocate more memory in the same way vector and other dynamic fields do. (-> constant amortized complexity). This operation always allocates memory at the end. So whenever you want to add something to the beginning of a string, you actually have to alter the argument that will be the new prefix or you have to construct an entirely new string.
operator+=forces you to alter the object that will prefix the resulting string. Creating an entirely new object (with memory allocation and completely copying both arguments) shouldn’t happen implicitly, anyway. If you want something likeb = a + bthis means thatbnow carries a newly constructed string. It’s a fresh assignment.operator+=, on the other hand, changes the left-hand-side argument.