我目前正尝试将一个std::unique_ptr存储在std::unordered_map中,但是我得到了一个奇怪的编译错误。 相关代码:
#pragma once
#include "Entity.h"
#include <map>
#include <memory>
class EntityManager {
private:
typedef std::unique_ptr<Entity> EntityPtr;
typedef std::map<int, EntityPtr> EntityMap;
EntityMap map;
public:
/*
Adds an Entity
*/
void addEntity(EntityPtr);
/*
Removes an Entity by its ID
*/
void removeEntity(int id) {
map.erase(id);
}
Entity& getById(int id) {
return *map[id];
}
};
void EntityManager::addEntity(EntityPtr entity) {
if (!entity.get()) {
return;
}
map.insert(EntityMap::value_type(entity->getId(), std::move(entity)));
}
这是编译错误:
c:\program files (x86)\microsoft visual studio 12.0\vc\include\tuple(438): error C2280: 'std::unique_ptr<Entity,std::default_delete<_Ty>>::unique_ptr(const std::unique_ptr<_Ty,std::default_delete<_Ty>> &)' : attempting to reference a deleted function
1> with
1> [
1> _Ty=Entity
1> ]
1> c:\program files (x86)\microsoft visual studio 12.0\vc\include\memory(1486) : see declaration of 'std::unique_ptr<Entity,std::default_delete<_Ty>>::unique_ptr'
1> with
1> [
1> _Ty=Entity
1> ]
1> This diagnostic occurred in the compiler generated function 'std::pair<const _Kty,_Ty>::pair(const std::pair<const _Kty,_Ty> &)'
1> with
1> [
1> _Kty=int
1> , _Ty=EntityManager::EntityPtr
1> ]
map.insert(EntityMap::value_type(entity->getId(), std::move(entity)))
本身就不安全,因为无法确定将entity
移动到函数参数中是在entity->getId()
求值之前还是之后。为了保险起见,应该将getId()
赋值给一个临时变量并将其传递给函数。 - Michael Burrstd
еә“зҡ„й—®йўҳгҖӮеҜ»жүҫй”ҷиҜҜжҠҘе‘ҠпјҢжҲ–иҖ…и®ҫзҪ®дёҖдёӘhttp://ssccr.org并жҸҗдәӨдёҖдёӘпјҹ - Yakk - Adam Nevraumontmap.insert(std::move(std::make_pair(entity->getId(), std::move(entity))));
或者尝试使用std::forward
。我之前也遇到过这个错误。我不记得我在VS2012中是如何解决它的,但我确定它涉及到了一个 forward 或 move。另一个选项是将 nullptr 插入到 map 中,然后使用索引运算符对其进行移动赋值。 - Brandonstd::unique_ptr<int> up(new int); std::unique_ptr<int> up2(std::move(up));
将int指针的所有权从up
转移到了up2
。 - Ryan Haining