std::string 的默认容量?
当我使用默认构造函数创建 std::string
时,堆上是否分配了任何内存?我希望答案不依赖于实施并且是标准化的。考虑以下几点:
std::string myString;
When I create a std::string
using the default constructor, is ANY memory allocated on the heap? I'm hoping the answer does not depend on the implementation and is standardized. Consider the following:
std::string myString;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
不幸的是,根据 N3290 的说法,答案是否定的。
表 63 第 643 页表示:
data()
一个可复制的非空指针,可以添加 0size()
0capacity() 未指定的值
该表与 C++03 相同。
Unfortunately, the answer is no according to N3290.
Table 63 Page 643 says:
data()
a non-null pointer that is copyable and can have 0 added to itsize()
0capacity()
an unspecified valueThe table is identical for C++03.
不,但是,而且我不知道有任何实现会默认在堆上分配内存。然而,不少都包含所谓的短字符串优化 (SSO),它们分配一些空间作为字符串对象本身的一部分,因此只要您不需要超过该长度(似乎在 10 之间)通常为 20 个字符),它可以完全避免进行单独的堆分配。
但这也不是标准化的。
No, but, and I don't know of any implementation that does allocate memory on the heap by default. Quite a few do, however, include what's called the short string optimization (SSO), where they allocate some space as part of the string object itself, so as long as you don't need more than that length (seems to be between 10 and 20 characters as a rule) it can avoid doing a separate heap allocation at all.
That's not standardized either though.
它取决于实现。某些字符串实现对小字符串使用少量自动分配的存储空间,然后为较大的字符串动态分配更多存储空间。
It is implementation dependent. Some string implementations use a small amount of automatically allocated storage for small strings, and then dynamically allocate more for larger strings.
这取决于编译器。看一下这里,有一个很好的解释:
http ://www.learncpp.com/cpp-tutorial/17-3-stdstring-length-and-capacity/
It depends on the compiler. Take a look here, there is a good explanation:
http://www.learncpp.com/cpp-tutorial/17-3-stdstring-length-and-capacity/
一般来说,是它们在堆上分配内存。我举一个例子:
c_str()
需要一个 NULL 尾随字符“\0”。大多数实现提前分配此 NUL\0
,作为字符串的一部分。因此,您将至少分配一个字节,通常更多。如果您确实需要特定的行为,我建议您编写自己的类。缓冲区/字符串类并不难编写。
Generally, yes they allocate memory on the heap. I'll give an example:
c_str()
requires a NULL trailing character '\0'. Most implementations allocate this NUL\0
ahead of time, as part of the string. So you'll get at least one byte allocated, often more.If you really need specific behavior I'd advise writing your own class. Buffer/string classes are not that hard to write.