C ++小字符串优化(SSO)如何与容器一起使用? [英] How could C++ Small String Optimized (SSO) work with containers?

查看:190
本文介绍了C ++小字符串优化(SSO)如何与容器一起使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

SSO解释说,小的字符串分配在堆上:好的,但是当在容器中构造这些内容时,这些内容不应放在堆栈上,因为容器可以在函数中创建并返回,而函数堆栈会过时。

The SSO explanation says the small strings are allocated on heap: OK, but when constructed inside containers, these contents shouldn't be on stack because containers can be created in function and return, while function stack goes stale.

所以我想SSO不能与STL容器一起使用吗?

So I guess SSO doesn't work with STL containers, does it?

推荐答案

小字符串和大字符串之间的区别不是将其存储在堆栈或堆上的区别。取而代之的是间接级别

The difference between "small string" and the "large string" is not the difference between storing it on the stack or on the heap. Instead what differs is the level of indirection.

这意味着 std :: string 对象可以保存一个指向实际字符串数据的指针,该指针可以(几乎)任何长度,但是具有间接动态内存的所有缺点-分配,释放,缓存未命中等。

What that means is std::string object can hold a pointer to the actual string data, which could be of (almost) any length, but has all the downsides of indirect dynamic memory - allocations, deallocations, cache misses etc.

或者SSO允许 std :: string std :: string 内部存储小字符串code>对象,无论它分配在哪里。如果对象位于字符串所在的某个容器中(在堆中),但不需要像大字符串那样的其他间接访问。

Alternatively SSO allows std::string to store small strings "in place", right inside thestd::string object, wherever it is allocated. If the object is in some container (on the heap) that's where the string will be, but it won't require another indirection as the large string would.

这篇关于C ++小字符串优化(SSO)如何与容器一起使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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