str.clear()和str =“”之间的区别(Difference between str.clear() and str = “”)

编程入门 行业动态 更新时间:2024-10-27 16:27:32
str.clear()和str =“”之间的区别(Difference between str.clear() and str = “”)

我有一个C ++ std::string str我已设置为某个字符串,现在想要重置,以便可以再次使用它。 调用str.clear() vs str = ""之间有区别吗?

编辑。 澄清一下:我通过在其中附加一个char数组缓冲区来重用str: str.append(buf)

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)

最满意答案

没有有效的区别。 根据实现的不同,使用clear()可能比分配给char指针为零更快。 不过,即使情况并非如此,您更喜欢更清楚表达意图的方法。 如果要清除字符串,请使用clear() 。 如果要分配空字符串,请使用= "" 。

虽然我会注意到,但你说,“所以我可以再次使用它。” 再用一次呢? 如果你只是把它分配给别的东西,就没有必要事先清除它。

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.

更多推荐

本文发布于:2023-07-26 16:44:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1278196.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:区别   str   clear   Difference

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!