矢量与unique_ptr-s

时间:2013-03-29 13:16:20

标签: c++ c++11 move-semantics

我有这样的代码:

#include <memory>
#include <vector>

namespace daq
{

class Animal
{
public:
    Animal(){};
};

class Pig : public Animal
{
public:
    Pig() : Animal () {};
};

class Farm
{
public:
    void addAnimal(Animal& animal)
    {
        mAnimals.push_back(std::unique_ptr<Animal>(animal)); // error
    }

private:
    std::vector<std::unique_ptr<Animal>> mAnimals;
};
} /* namespace daq */

但是我在方法Farm :: addAnimal中遇到错误:

没有匹配函数来调用'std :: unique_ptr :: unique_ptr(daq :: Animal&amp;)'

我应该将什么传递给push_back方法?

1 个答案:

答案 0 :(得分:3)

unique_ptr接受指针作为构造函数参数,但您传递引用。这基本上就是编译器告诉你的:你不能从std::unique_ptr构造daq::Animal&

您可以将原始指针传递给分配有Animal的{​​{1}}类型的对象,或者(最好)您应该传递new这样构造并且从中移动将其作为unique_ptr

的参数提供
push_back()

你必须在这里使用void addAnimal(std::unique_ptr<Animal>&& animal) // ^^ // This is to make it absolutely clear that // your intention is to bind to an object // the client wants to move from. It is not // especially needed here (unique_ptr is not // copyable), but it makes your interface // more explicit about it. [Credits to sehe] { mAnimals.push_back(std::move(animal)); // OK } int main() { daq::Farm farm; std::unique_ptr<daq::Animal> pig(new daq::Pig()); farm.addAnimal(std::move(pig)); // OK } 因为std::move()是不可复制的,所以你有效地将unique_ptr的所有权从调用它的例程转移到包含它的向量(pig是此转移的中间人。)