简体   繁体   English

在多重继承中使用 std::unique_ptr

[英]Using std::unique_ptr in multiple inheritance

I'm writing a program that runs a simulation with two types of Animals - Wolfes and Rabbits.我正在编写一个程序,该程序运行模拟两种动物 - 狼和兔子。 In my code i have virtual interface class IAnimal, and base class called Animal.在我的代码中,我有虚拟接口类 IAnimal 和名为 Animal 的基类。 So, in one part of code, I need to make new instances of my animals, and I wrote this:所以,在代码的一部分中,我需要为我的动物制作新的实例,我写了这个:

void Simulation::age_and_multiply_and_die() {
for (auto *animal: animals) {
    if (animal->is_dead()) continue;
    animal->aging();
    if (animal->must_multiply()) {
        switch (animal->get_type()) {
            case Type::Rabbit: {
                spawn_animal(new Rabbit((Animal *) animal, *this));
                break;
            }
            case Type::Wolf: {
                spawn_animal(new Wolf((Animal *) animal, *this));
                ((Wolf *) animal)->hungry_again();
                break;
            }
        }
    }

where spawn_animal() is:其中 spawn_animal() 是:

void spawn_animal(IAnimal *animal) {
    animals.push_back(animal);
    Coords pos = animal->get_position();
    field[pos.y][pos.x].push_back(animal);
}

so, i want to get rid of switch statement and use unique_ptr to make something like this:所以,我想摆脱 switch 语句并使用 unique_ptr 来做这样的事情:

class IAnimal {

public:

    virtual Coords get_position() = 0;

    virtual std::unique_ptr<IAnimal> breed() = 0;
...

void Simulation::age_and_multiply_and_die() {
for (auto *animal: animals) {
    if (animal->is_dead()) continue;
    animal->aging();
    if (animal->must_multiply()) {
      IAnimal child = animal.breed();
      if (child)
          animals.push_back(child);
      }
    }

how can i do this?我怎样才能做到这一点?

Your breed method returns a unique_ptr , so you should write your calling code to receive a unique_ptr :您的breed方法返回一个unique_ptr ,因此您应该编写您的调用代码来接收一个unique_ptr

std::unique_ptr<IAnimal> child = animal.breed();

Because unique_ptr doesn't support copying, you should move it when inserting into your data structure:因为unique_ptr不支持复制,所以在插入数据结构时应该move它:

if (child)
{
      animals.push_back(std::move(child));
}

Note: your code modifies a container it iterates on.注意:您的代码修改了它迭代的容器。 This is forbidden and will lead to tricky problems.这是被禁止的,会导致棘手的问题。 Instead of that, create a new vector , fill it in your loop, and only afterwards discard the old vector .取而代之的是,创建一个新的vector ,将其填充到您的循环中,然后才丢弃旧的vector

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM