我如何用智能指针动态升起和降低

How do I dynamic upcast and downcast with smart pointers?

本文关键字:升起 动态 指针 何用 智能      更新时间:2023-10-16

我有一些代码,带有一个通用接口,我需要上下施放。我现在正在尝试转换为智能指针,但遇到了一些错误。下面的代码重现了问题。我正在使用C 14,所以我认为现在应该自动起作用?

#include <memory>
#include <iostream>
int main()
{
    std::shared_ptr<int> a(new int);
    *a = 5;
    std::shared_ptr<void> b = std::dynamic_pointer_cast<void>(a);
    std::shared_ptr<int> c = std::dynamic_pointer_cast<int>(b);
    std::cout << *c; //should be 5
    return 0;
}

但是,当我尝试编译时,我会得到:

Error   C2680   '_Elem1 *': invalid target type for dynamic_cast    
Error   C2681   'int *': invalid expression type for dynamic_cast   

猜测我在语法中做了一些愚蠢的事情?

规则与愚蠢的指针相同,除非您必须使用std::static_pointer_caststd::dynamic_pointer_cast而不是static_castdynamic_cast。C 17将引入reinterpret_cast的对应物,但对于上或向下铸件不需要,也不需要转换为void。

我如何动态启动...智能指针?

类型层次结构中的转换是隐式的,因此不需要铸造:

struct A{
    virtual ~A(){}
};
struct B:A{};
auto b = std::make_shared<B>();
std::shared_ptr<A> a = b;

我如何动态...用智能指针降低?

如果您不确定源是否指向正确的类型,请使用std::dynamic_pointer_cast。仅当继承是多态性的时才(即,基数至少具有一个虚拟函数(:

b = std::dynamic_pointer_cast<B>(a);

std::static_pointer_cast如果您知道类型正确:

b = std::static_pointer_cast<B>(a);

std::shared_ptr<void> b = std::dynamic_pointer_cast<void>(a);
std::shared_ptr<int> c = std::dynamic_pointer_cast<int>(b);

voidint没有继承关系,因此不能向上或向下施放。

但是,所有指针都可以隐式转换为空隙指针,因此可以隐含的转换:

 std::shared_ptr<void> b = a;

,并且可以将void指针静态地铸造为原始类型,因此您可以使用std::static_pointer_cast

std::shared_ptr<int> c = std::static_pointer_cast<int>(b);

自C 17以来,您有std::reinterpret_pointer_cast