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

时光怂恿深爱的人放手 提交于 2019-12-10 15:36:46

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!