我听说 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 spanslen
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 positionpos
and spanslen
characters (or until the end ofstr
, if eitherstr
is too short or iflen
isbasic_string::npos
).
进一步测试 GNU 的实现,显然复制构造函数确实使用了引用计数,而子字符串构造函数没有。
关于c++ - `substr` 是否使用相同的底层内存?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27286432/