是否允许unique_prts隐式转换其包含类型

Are unique_prts allowed to implicitly convert their containing type?

本文关键字:转换 包含 类型 prts unique 是否      更新时间:2023-10-16

有人能解释一下为什么我的factory函数是正确的吗?默认情况下,unique_ptr是否执行动态强制转换?为什么返回类型不必与factory函数类型相同?

#include <exception>
#include <iostream>
#include <memory>
struct Animal
{
  virtual void makeSound() { std::cout << "(...)" << std::endl; }
};
struct Cat : public Animal
{
  virtual void makeSound() { std::cout << "Meaw!" << std::endl; }
};
struct Dog: public Animal
{
  virtual void makeSound() { std::cout << "Woof!" << std::endl; }
};
struct ConfusedCat : public Cat
{
  virtual void makeSound() { std::cout << "Moooooh!" << std::endl; }
};
// Why is this factory function allowed like this?
std::unique_ptr<Animal> factory(const int i)
{
  if (i == 1)
    return std::unique_ptr<Cat>(new Cat());
  else if (i == 2)
    return std::unique_ptr<ConfusedCat>(new ConfusedCat());
  else if (i == 3)
    return std::unique_ptr<Dog>(new Dog());
  else
    return std::unique_ptr<Animal>(new Animal());
}
int main()
{
  try
  {
    auto animal0 = factory(0);
    auto animal1 = factory(1);
    auto animal2 = factory(2);
    auto animal3 = factory(3);
    animal0->makeSound();
    animal1->makeSound();
    animal2->makeSound();
    animal3->makeSound();
  }
  catch ( std::exception &e )
  {
    std::cout << e.what() << std::endl;
    return 1;
  }
  return 0;
}

在C++中,派生到公共基指针的转换是隐式的,不需要强制转换。

所有标准和boost智能指针也是如此。

参见std::unique_ptr::unique_ptr:上的过载6

std::unique_ptr<Derived>可隐式转换为std::unique_ptr<基本>通过过载(6)