是否允许unique_prts隐式转换其包含类型
Are unique_prts allowed to implicitly convert their containing type?
有人能解释一下为什么我的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)
相关文章:
- 如何将包含epoch时间的十六进制字符串转换为time_t
- 在混合代码库中将C转换为C++时出现许多包含错误
- C++如何乘以包含 std::variant 元素的向量的迭代器?正在执行迭代器类型的转换?
- 如何将包含指数的 QString 转换为C++中的双倍?
- 无法将字符数组转换为包含 utf-8 字符的字符串
- 转换包含向量 C++ 的语法和结构
- 将包含多个元素的字符串作为输入并转换为矢量 C++
- 如何为代码包含负值?号码系统转换
- C++将包含非人类可读数据的字符串转换为 200 双精度
- 包含可变参数包的第一个可转换类型的别名的结构
- C++要包含在词法强制转换中的头文件
- 无法转换 .CATPart 文件.错误:输入文件路径似乎包含不支持的字符
- 如果必须包含西里尔字符,如何将 char* 转换为 std::string?
- 如何将包含中文或韩语的字符串转换为十六进制/字节
- 如何将智能指针向量转换为常量向量,该常量向量包含指向常量的智能指针
- 如何在将秒转换为分钟且余数小于 10 秒时包含前导零
- 如何在C++中将边列表转换为邻接矩阵,其中包含连接到顶点的边数而不是一条边?
- 如何将包含 '