我有一个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.
更多推荐
发布评论