【发布时间】:2018-11-08 06:06:20
【问题描述】:
我正在调查移动std::string 的性能。很长一段时间以来,我一直认为字符串移动几乎是免费的,认为编译器会内联所有内容,并且只涉及一些廉价的赋值。
事实上,我移动的心智模式确实是
string& operator=(string&& rhs) noexcept
{
swap(*this, rhs);
return *this;
}
friend void swap(string& x, string& y) noexcept
{
// for disposition only
unsigned char buf[sizeof(string)];
memcpy(buf, &x, sizeof(string));
memcpy(&x, &y, sizeof(string));
memcpy(&y, buf, sizeof(string));
}
据我所知,如果将 memcpy 更改为分配单个字段,则这是一种合法的实施方式。
发现gcc的移动实现涉及creating a new string and might possibly throw due to the allocations despite being noexcept,让我大吃一惊。
这是否符合要求?同样重要的是,我不应该认为搬家几乎是免费的吗?
令人困惑的是,std::vector<char> compiles down 符合我的预期。
clang's implementation 有很大不同,虽然有一个可疑的std::string::reserve
【问题讨论】:
-
使用 SSO(短字符串优化)移动可以复制,因为您无法移动数组。
-
@NathanOliver 我知道,但
memcpy涵盖了这一点。至少,我希望有一个大小为sizeof(string)的缓冲区用于临时复制数组的内容,而不是创建临时字符串 -
将`-stdlib=libc++`添加到clang窗口。
-
你仍然在 libc++ 中发现了一个错误!
basic_string::__clear_and_shrink()应标记为noexcept。有了这个添加,移动赋值运算符就可以很好地清理了。 -
__clear_and_shrink显然是最近的编辑。我正在查看 libc++ 的尖端:github.com/llvm-mirror/libcxx/blob/master/include/…
标签: c++ string move-semantics