C++中的“moving”不会删除元素,它只是在使用它们创建新对象时使用move构造函数,对于普通类型,它只会复制它们,但对于包含以下资源的对象
unique_ptr
或
vector
移动构造函数将正确地窃取托管资源,您可以声明一个移动构造函数来查看它是否被调用。
最后,你不能动
const
对象(请参见move构造函数声明)
const auto& kv
需要更改为
auto& kv
在你的
transform
,然后您需要清除“移出”对象的映射。
#include <algorithm>
#include <cstdint>
#include <iostream>
#include <map>
#include <vector>
struct Values
{
uint32_t a = 0;
uint32_t b = 0;
Values(const Values&) { std::cout << "copied!\n"; }
Values(Values&&) { std::cout << "moved!\n"; }
Values(uint32_t x, uint32_t y) : a(x), b(y) {}
};
template <typename MapType>
auto foo(MapType&& map)
{
std::vector<typename MapType::value_type> v;
v.reserve(map.size());
std::transform(map.begin(), map.end(), std::back_inserter(v), [](auto& kv) -> decltype(auto) { return std::move(kv); });
map.clear(); // clear map content which has been "moved from"
std::cout << map.size() << " " << v.size() << "\n";
}
int main()
{
std::map<uint32_t, Values> data;
for (uint32_t i = 0; i < 100; i++)
data.emplace(std::piecewise_construct, std::forward_as_tuple(i), std::forward_as_tuple(2 * i, 3 * i));
foo(std::move(data));
return 0;
}
你会看到100
moved
打印有
auto&
和100
copied
打印有
const auto&