c++ - `substr` 是否使用相同的底层内存?

标签 c++ libstdc++

我听说 std::string 使用底层引用计数器来避免复制 std::string 数据。

substr 方法是使用它还是创建原始 std::string 的拷贝?

由于它是非常特定于实现的,所以让我们首先关注 GNU 的实现。

最佳答案

来自 cplusplus.com,string::substr()引用文献(强调):

Generate substring

Returns a newly constructed string object with its value initialized to a copy of a substring of this object.

The substring is the portion of the object that starts at character position pos and spans len characters (or until the end of the string, whichever comes first).

一窥 GNU 的实现表明它确实构造了一个新字符串,使用 substring constructor :

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);

substring constructor

Copies the portion of str that begins at the character position pos and spans len characters (or until the end of str, if either str is too short or if len is basic_string::npos).


进一步测试 GNU 的实现,显然复制构造函数确实使用了引用计数,而子字符串构造函数没有。

关于c++ - `substr` 是否使用相同的底层内存?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27286432/

相关文章:

c++ - 派生类的模板参数推导

c++ - 为什么 std::seed_seq 根据 C++11 是不可复制的,为什么 gcc/clang 不符合?

c++ - std::vector 构造函数行为

c++ - gcc 4.8 或更早版本是否存在关于正则表达式的问题?

c++ - 使用哪个版本的 libstdc++.so.6?

c++ - 应用程序可以依赖两个不同版本的 libstdc++ 吗?

c++ - 有没有一种通用的方法可以从所有类属性中创建一个元组?

c# - Java 线程创建性能 vs C# 线程创建性能 vs C++( native 线程)?

c++ - Xcode/LLVM catch 子句不匹配派生类型

c++ - 当子进程不刷新其标准输出时如何从子进程读取标准输出?