gpt4 book ai didi

c++ - 用于自追加的字符串反向迭代器的持久性

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:26:33 24 4
gpt4 key购买 nike

问题:

假设我有一个字符串,我想生成一个新字符串,其中包含原始字符串及其反向连接。

以下是否保证有效?

auto pq = [](std::string &s){
s.reserve(2*s.size());
s.append(s.rbegin(), s.rend());
};

我看到了 reserve应该设置 capacity适本地。但是,是否应用 append反对反向迭代器会导致这些迭代器失效?

其他背景:

我的 C++.11 拷贝(与 C++.17 draft 具有相同的语言),在 §[string.capacity] 中说

void reserve(size_type res_arg=0);

  1. The member function reserve() is a directive that informs a basic_string object of a planned change in size, so that it can manage the storage allocation accordingly.
  2. Effects: After reserve(), capacity() is greater or equal to the argument of reserve. [ Note: Calling reserve() with a res_arg argument less than capacity() is in effect a non-binding shrink request. A call with res_arg <= size() is in effect a non-binding shrink-to-fit request. — end note ]
  3. Throws: length_error if res_arg > max_size().227

227) reserve() uses allocator_traits::allocate() which may throw an appropriate exception.

同时,§[string.append] 说

basic_string&
append(const charT* s, size_type n);

  1. Requires: s points to an array of at least n elements of charT.
  2. Throws: length_error if size() + n > max_size().
  3. Effects: The function replaces the string controlled by *this with a string of length size() + n whose first size() elements are a copy of the original string controlled by *this and whose remaining elements are a copy of the initial n elements of s.
  4. Returns: *this.

最佳答案

这不是 std::string::append 的重载你实际上打电话。您调用的是 template<class InputIterator> basic_string& append(InputIterator first, InputIterator last); .在那里,标准说 ( [string.append]/21 ) 它等同于在附加之前构造一个新字符串:

Effects: Equivalent to append(basic_­string(first, last, get_­allocator())).

注意这里,构造函数调用basic_­string(first, last, get_­allocator())在调用不同的 append 重载之前 创建一个临时字符串,因此无论在另一个 append 中发生什么重新分配无关紧要。这意味着,即使不调用 reserve首先,这应该是安全的。

请注意,不能保证字符串就是这样实现的;该标准说“等同于”,而不是“实现为”。该实现可以执行任何具有相同结果的操作,但在这种情况下,“相同结果”意味着它仍然需要使用从调用它的相同字符串派生的迭代器。

关于c++ - 用于自追加的字符串反向迭代器的持久性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50456183/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com