Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is there 'clear' method when "" can be assigned to std::string?

Tags:

c++

string

One can use string::clear function to empty a string, and can use empty double quotation "" to do that also. What is the difference?

like image 597
AliOsm Avatar asked Feb 14 '16 06:02

AliOsm


People also ask

Can we clear a string in C++?

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.

Does std::string clear free memory?

Problem Description. The String::clear() function does only set the length to 0, it does not free the memory.

Is std::string allocated on the heap?

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.


1 Answers

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.

like image 104
cdonat Avatar answered Sep 21 '22 18:09

cdonat