我正在玩不同的智能指针并遇到问题。
我有一个Environment
抽象类和一个继承Environment
的基础类:
class Ground : public Environment
{
protected:
std::string type;
int damage;
public:
Ground() : Environment()
{
this->type = "ground";
}
virtual void SetDamage(int _damage)
{
this->damage = _damage*5;
}
virtual std::string& GetType()
{
return this->type;
}
virtual int GetDamage()
{
return this->damage-10;
}
virtual ~Ground(){}
};
我还有一个继承Dirt
类的Ground
类:
class Dirt : public Ground
{
public:
Dirt() : Ground()
{
this->type = "dirt";
}
void SetDamage(int _damage)
{
this->damage = _damage*6;
}
int GetDamage()
{
return this->damage-20;
}
~Dirt()
{
}
private:
};
现在,如果我想在std::vector
这样的内容中使用它:
std::vector<std::unique_ptr<Ground>> listGround;
std::unique_ptr<Ground> ground(new Ground());
listGround.push_back(ground);
std::unique_ptr<Dirt> dirt(new Dirt());
listGround.push_back(dirt); // FAIL
for (auto i = listGround.begin(); i != listGround.end(); i++)
{
(*i)->SetDamage(80);
std::cout << (*i)->GetType() << " " << (*i)->GetDamage() << std::endl;
}
listGround.empty();
我收到一个编译错误,说没有可用的用户定义转换运算符,可以在上面代码中标记为FAIL的行上执行此转换等。
如果我使用std::shared_ptr
,一切都按预期工作。原始指针也是如此。
为什么我收到此错误?
错误C2664:&#39; void std :: vector&lt; _Ty&gt; :: push_back(std :: unique_ptr &安培;&安培;)&#39; :无法从&#39; std :: unique_ptr&lt; _Ty&gt;&#39;转换参数1至 &#39;的std ::的unique_ptr&LT; _Ty&GT; &安培;&安培;&#39; 1 GT;用1> [1> _Ty = std :: unique_ptr 1&gt; ] 1&gt;和1> [1> _Ty =污垢1&gt; ] 1&gt;和1> [ 1 GT; _Ty =地面1&gt; ] 1&gt;原因:不能 转换自&#39; std :: unique_ptr&lt; _Ty&gt;&#39; to&#39; std :: unique_ptr&lt; _Ty&gt;&#39; 1 GT;
用1> [1> _Ty =污垢1&gt; ] 1&gt;
和1> [1> _Ty =地面1&gt; ] 1&gt;
没有可用于执行此操作的用户定义转换运算符 转换,或者不能调用运算符
答案 0 :(得分:1)
创建适当的东西:
listGround.emplace_back(new Dirt());
这不是shared_ptr
,但您尝试在dirt
和listGround.back()
之间共享所有权
答案 1 :(得分:1)
std::vector::push_back
要求传递的类型是可复制的(或者在C ++ 11中可移动)并且std::unique_ptr
不可复制。这就是错误消息告诉您它缺少相应的移动转换。您可以使用std::unique_ptr
函数移动std::move
,该函数只是将相应的强制转换为正确的r引用类型。