std::sort
和std::ranges::sort' lead to underlying context of
std::stringcopying during sorting while
std::swapjust exchanges the pointers in the
std::string`的具体原因是什么?
请参阅演示,地址如下:
#include <algorithm>
#include <iostream>
#include <string>
#include <vector>
int main()
{
std::vector<std::string> arr = { "You", "HereIJustWantToHaveMemoryReallocation", "See" };
std::cout << "\nBefore sorting:";
for (auto& s : arr) {
std::cout << "\nString:" << s << " at " << std::addressof(s) << " points to " << (void*)(s.c_str());
}
std::sort(arr.begin(), arr.end());
std::cout << "\nAfter sorting:";
for (auto& s : arr) {
std::cout << "\nString:" << s << " at " << std::addressof(s) << " points to " << (void*)(s.c_str());
}
}
问题不是如何避免这种情况,这很容易做到,例如使用
std::string_view
。问题是为什么std::sort
和std::ranges::sort
会这样?
我希望排序算法使用 std::swap 或某种移动语义,这将允许 std::string 仅交换指向底层字符串的指针,而不接触字符串本身。为什么不是这样?
对于长字符串,它不使用小字符串优化,因此指向字符串数据的指针保持不变。在这种情况下,交换实际上只是转移了两个
std::string
之间的所有权。
对于较短的字符串,使用小字符串优化,数据指针实际上是
std::string
对象本身内部的指针。因此,每个 std::string
的指针都是唯一的,不能移动到另一个 std::string
。