问题
One can use string::clear
function to empty a string, and can use empty double quotation "" to do that also. What is the difference?
回答1:
When you assign an empty string, the compiler will have to store an empty C-string in the data section, and create the code to pass a pointer to it to the assignment operator. The assignment operator then has to read from the data section, just to find out, that you passed an empty string.
With clear()
the compiler just generates a function call without any parameters. No empty string in the data section, no passing of a pointer, no reading, etc.
You might even have a compiler, that can optimize that out. I don't know if there are any, but the standard library can not rely on specific compiler capabilities, that are not required.
An even more important difference is in expressing the intent. When you want the reader of your code to understand, that the string will be cleared, use clear()
. When the intent is to assign a new value to your string, that accidentially is an empty string, then use the assignment operator.
来源:https://stackoverflow.com/questions/35388912/why-is-there-clear-method-when-can-be-assigned-to-stdstring