我听说std::string使用底层引用计数器来避免复制std::string数据。
该substr方法是使用它还是创建原始副本std::string?
由于它是非常具体的实现,让我们首先关注 GNU 的实现。
来自 cplusplus.comstring::substr()的参考(强调):
生成子串
返回一个新构造的字符串对象,其值初始化为此对象的子字符串的副本。
子字符串是对象的从字符位置开始
pos并跨越len字符的部分(或直到字符串的结尾,以先到者为准)。
窥视 GNU 的实现表明它确实使用子字符串构造函数构造了一个新字符串:
basic_string (const basic_string& str, size_type pos, size_type len = npos,
const allocator_type& alloc = allocator_type());
// or string (const string& str, size_t pos, size_t len = npos);
Run Code Online (Sandbox Code Playgroud)
子串构造器
份的所述部分
str开头处的字符位置pos和跨度len字符(或直到结束str,如果有一个str过短,或者如果len是basic_string::npos)。
进一步测试 GNU 的实现,显然复制构造函数确实使用了引用计数,而子字符串构造函数则没有。