如何使用glibc的字符串实现在堆栈上分配std :: string? [英] How do I allocate a std::string on the stack using glibc's string implementation?

查看:73
本文介绍了如何使用glibc的字符串实现在堆栈上分配std :: string?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

int main(void)
{
   std::string foo("foo");
}

我的理解是,上面的代码使用默认的分配器来调用new.因此,即使std :: string foo分配在堆栈上,foo内部的内部缓冲区也分配在堆上.

My understanding is that the above code uses the default allocator to call new. So even though the std::string foo is allocated on the stack the internal buffer inside of foo is allocated on the heap.

如何创建一个完全在堆栈上分配的字符串?

How can I create a string that is allocated entirely on the stack?

推荐答案

我最近想自己做一下,发现下面的代码可以说明问题:

I wanted to do just this myself recently and found the following code illuminating:

Chronium的stack_container.h

它定义了一个新的std::allocator,它可以为基于STL容器的存储的初始分配提供基于堆栈的分配.我最终想找到一种解决我特定问题的方法,所以我实际上并未亲自使用该代码,但也许对您有用.请务必阅读代码中有关用法和注意事项的注释.

It defines a new std::allocator which can provide stack-based allocation for the initial allocation of storage for STL containers. I wound up finding a different way to solve my particular problem, so I didn't actually use the code myself, but perhaps it will be useful to you. Do be sure to read the comments in the code regarding usage and caveats.

对于那些质疑这样做的实用性和合理性的人,请考虑:

To those who have questioned the utility and sanity of doing this, consider:

  • 通常您会先验地知道您的字符串具有合理的最大大小.例如,如果字符串将存储一个十进制格式的32位整数,则您知道不需要多于11个字符.在这种情况下,不需要可以动态增长为无限大小的字符串.
  • 在许多情况下,从堆栈分配比从堆分配更快.
  • 如果频繁创建和销毁字符串(假设它是常用的实用程序函数中的局部变量),则从堆栈而不是堆进行分配将避免在堆分配器中产生碎片.对于使用大量内存的应用程序,这可能会改变游戏规则.

有人评论说,使用基于堆栈的分配的字符串将不是std::string,就好像这在某种程度上削弱了它的效用.的确,您不能将两者互换使用,因此您将无法将stackstring传递给需要std::string的函数.但是(如果操作正确),您将可以在stackstring上使用现在在std::string上使用的所有相同成员函数,例如find_first_of()append()等.begin()end()仍然可以正常工作,因此您将能够使用许多STL算法.当然,从最严格的意义上讲,它不是std::string,但从实际意义上讲,它仍然是字符串",并且仍然会非常有用.

Some people have commented that a string that uses stack-based allocation will not be a std::string as if this somehow diminishes its utility. True, you can't use the two interchangeably, so you won't be able to pass your stackstring to functions expecting a std::string. But (if you do it right), you will be able to use all the same member functions on your stackstring that you use now on std::string, like find_first_of(), append(), etc. begin() and end() will still work fine, so you'll be able to use many of the STL algorithms. Sure, it won't be std::string in the strictest sense, but it will still be a "string" in the practical sense, and it will still be quite useful.

这篇关于如何使用glibc的字符串实现在堆栈上分配std :: string?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆