Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between str.clear() and str = ""

I have a C++ std::string str that I've set to some string, and now want to reset so it can be used again. Is there a difference between calling str.clear() vs str = ""?

EDIT. To clarify: I'm reusing str by appending a char array buffer to it: str.append(buf)

like image 569
trong Avatar asked Mar 13 '23 01:03

trong


1 Answers

There is no effective difference. Depending on the implementation, using clear() may be faster than assigning to a char pointer to zero. Even if this were not the case, though, prefer the method that more clearly expresses your intent. If you want to clear the string, use clear(). If you want to assign an empty string, use = "".

Though I will note, you said, "so I can use it again." Use it again for what? If you are just assigning it to something else, there's no need to clear it beforehand.

like image 53
md5i Avatar answered Mar 15 '23 03:03

md5i