Reputation: 67
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)
Upvotes: 4
Views: 1629
Reputation: 3083
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.
Upvotes: 7