我的问题是安全问题。我搜索了cplusplus.com和cppreference.com,他们似乎缺乏std :: move期间的迭代器安全性。具体来说:使用已移动对象的迭代器调用std :: unordered_map :: erase(iterator)是否安全?示例代码:
#include <unordered_map>
#include <string>
#include <vector>
#include <iostream>
#include <memory>
class A {
public:
A() : name("default ctored"), value(-1) {}
A(const std::string& name, int value) : name(name), value(value) { }
std::string name;
int value;
};
typedef std::shared_ptr<const A> ConstAPtr;
int main(int argc, char **argv) {
// containers keyed by shared_ptr are keyed by the raw pointer address
std::unordered_map<ConstAPtr, int> valued_objects;
for ( int i = 0; i < 10; ++i ) {
// creates 5 objects named "name 0", and 5 named "name 1"
std::string name("name ");
name += std::to_string(i % 2);
valued_objects[std::make_shared<A>(std::move(name), i)] = i * 5;
}
// Later somewhere else we need to transform the map to be keyed differently
// while retaining the values for each object
typedef std::pair<ConstAPtr, int> ObjValue;
std::unordered_map<std::string, std::vector<ObjValue> > named_objects;
std::cout << "moving..." << std::endl;
// No increment since we're using .erase() and don't want to skip objects.
for ( auto it = valued_objects.begin(); it != valued_objects.end(); ) {
std::cout << it->first->name << "\t" << it->first.value << "\t" << it->second << std::endl;
// Get named_vec.
std::vector<ObjValue>& v = named_objects[it->first->name];
// move object :: IS THIS SAFE??
v.push_back(std::move(*it));
// And then... is this also safe???
it = valued_objects.erase(it);
}
std::cout << "checking... " << named_objects.size() << std::endl;
for ( auto it = named_objects.begin(); it != named_objects.end(); ++it ) {
std::cout << it->first << " (" << it->second.size() << ")" << std::endl;
for ( auto pair : it->second ) {
std::cout << "\t" << pair.first->name << "\t" << pair.first->value << "\t" << pair.second << std::endl;
}
}
std::cout << "double check... " << valued_objects.size() << std::endl;
for ( auto it : valued_objects ) {
std::cout << it.first->name << " (" << it.second << ")" << std::endl;
}
return 0;
}
我问的原因是,从unordered_map的迭代器中移动对可能(?)因此*重新移动迭代器存储的键值,因此使其散列无效;因此,之后的任何操作都可能导致未定义的行为。除非那不是这样吗?
我认为值得注意的是,上述内容似乎已成功按照GCC 4.8.2的规定运行,所以我希望看看我是否错过了支持或明确不支持该行为的文档。
答案 0 :(得分:5)
// move object :: IS THIS SAFE??
v.push_back(std::move(*it));
是的,它是安全的,因为它实际上并没有修改密钥。它不能,因为键是const。 *it
的类型为std::pair<const ConstAPtr, int>
。移动时,第一个成员(const ConstAPtr
)实际上没有移动。它会被std::move
转换为r值,并变为const ConstAPtr&&
。但这与移动构造函数不匹配,后者需要非const ConstAPtr&&
。所以改为调用复制构造函数。