我有一个类层次结构,其中B是从A派生的,如下所示:

class A : public std::enable_shared_from_this<A>
{

};

class B : public A
{
   void f()
   {
        // the code below compiles
        std::shared_ptr<B> copyOfThis = std::static_pointer_cast<B>(shared_from_this());
        // the code below does not
        std::shared_ptr<B> copyOfThis = static_cast<std::shared_ptr<B>>(std::make_shared<A>(shared_from_this()));
}
};

因此,实际上我想了解为什么当它实际上包含子级的static_cast时,为什么不能使用shared_ptr将父级的this转换为子级的原因。

编辑:看这个问题:Polymorphic smart pointer usage在这里,我问了为什么 child 的共享指针可以强制转换为父共享指针。答案是有一个模板构造函数。查看问题中的详细信息。那么,即使shared_ptr<A>shared_ptr<B>之间没有关系,为什么此构造函数也无助于强制转换。

最佳答案

您不能将shared_ptr<A>转换为shared_ptr<B>,因为类型之间没有继承关系。出于相同的原因,您不能将vector<A>转换为vector<B>

用相关类型实例化类模板不会使模板实例化也相关。
shared_ptr<T>(const shared_ptr<Y>&)构造函数无济于事,因为仅当Y*可隐式转换为T*时才可用,即它在那里支持与隐式发生的指针转换相同的指针转换,例如B*A*,而不是A*B*

您可以执行以下操作:

shared_ptr<A> thisA = shared_from_this();
shared_ptr<B> thisB(thisA, static_cast<B*>(thisA.get()));

这将创建一个与shared_ptr<B>共享所有权的thisA,并保存指针static_cast<B*>(thisA.get())
这正是static_pointer_cast<B>(thisA)所做的,但是上面使用的别名构造函数后来被添加到shared_ptr中,因此在发明static_pointer_cast时不存在,因此也不清楚它在做什么。 static_pointer_cast更具表现力。如果要对指针类型执行静态转换,请使用static_pointer_cast

关于c++ - std::static_pointer_cast与static_cast <std::shared_ptr <A >>,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/34048692/

10-11 22:33
查看更多