如何实现std :: string? [英] How is std::string implemented?

查看:117
本文介绍了如何实现std :: string?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很好奇知道std :: string是如何实现的,它如何与c string不同?如果标准没有指定任何实现,那么任何具有解释的实现都将很好地满足标准?

I am curious to know how std::string is implemented and how does it differ from c string?If the standard does not specify any implementation then any implementation with explanation would be great with how it satisfies the string requirement given by standard?

推荐答案

实际上,我使用的每个编译器都提供了运行时的源代码 - 无论您使用GCC还是MSVC,无论如何,你有能力看看实现。但是, std :: string 的很大一部分或全部将被实现为模板代码,这可能使阅读非常困难。

Virtually every compiler I've used provides source code for the runtime - so whether you're using GCC or MSVC or whatever, you have the capability to look at the implementation. However, a large part or all of std::string will be implemented as template code, which can make for very difficult reading.

Scott Meyer的书Effective STL有一章关于std :: string实现,它是一个体面的常见变化的概述:项目15:注意 string 实现中的变化。

Scott Meyer's book, Effective STL, has a chapter on std::string implementations that's a decent overview of the common variations: "Item 15: Be aware of variations in string implementations".

4个变体:


  • 一个ref计数实现(通常称为copy on write)复制不变,引用计数增加,但实际字符串数据不增加。两个对象都指向相同的引用计数数据,直到其中一个对象修改它,导致数据的写入时拷贝。变化存储在诸如引用计数,锁等等的地方。

  • several variations on a ref-counted implementation (commonly known as copy on write) - when a string object is copied unchanged, the refcount is incremented but the actual string data is not. Both object point to the same refcounted data until one of the objects modifies it, causing a 'copy on write' of the data. The variations are in where things like the refcount, locks etc are stored.

短字符串优化(SSO)实现。在这个变体中,对象包含通常的数据指针,长度,动态分配的缓冲区的大小等。但是如果字符串足够短,它将使用该区域来保存字符串,而不是动态分配缓冲区

a "short string optimization" (SSO) implementation. In this variant, the object contains the usual pointer to data, length, size of the dynamically allocated buffer, etc. But if the string is short enough, it will use that area to hold the string instead of dynamically allocating a buffer

此外, Herb Sutter's 更多特殊C ++有一个附录(附录A:不在多线程世界中的优化),讨论为什么在写多个线程的应用程序中,由于同步问题,写入引用计数的实现经常有性能问题。该文章也可以在线(但我不知道它是否与本书中的一样):

Also, Herb Sutter's "More Exceptional C++" has an appendix (Appendix A: "Optimizations that aren't (in a Multithreaded World)") that discusses why copy on write refcounted implementations often have performance problems in multithreaded applications due to synchronization issues. That article is also available online (but I'm not sure if it's exactly the same as what's in the book):

  • http://www.gotw.ca/publications/optimizations.htm

这两章都值得一读。

这篇关于如何实现std :: string?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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