One can use string::clear
function to empty a string, and can use empty double quotation "" to do that also. What is the difference?
std::string::clear in C++ The string content is set to an empty string, erasing any previous content and thus leaving its size at 0 characters.
Problem Description. The String::clear() function does only set the length to 0, it does not free the memory.
On Windows platform, in C++, with std::string, string size less than around 14 char or so (known as small string) is stored in stack with almost no overhead, whereas string size above is stored in heap with overhead.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With