多态智能指针使用 [英] Polymorphic smart pointer usage

查看:125
本文介绍了多态智能指针使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

到现在为止,我有一个函数,得到类型 IArg 的参数,我可以做以下:

Until now I have had a function that was getting an argument of type IArg and I could do the following:

struct IArg
{
};

struct Arg : IArg
{
};

void f (IArg* arg)
{
// do something
}

f(new Arg);

现在当我有这个:

void f (std::shared_ptr<IArg> arg)
{
// do something
}

为什么与

f(std::make_shared<Arg>());

std :: shared_ptr< A> std :: shared_ptr< B> 是不同类型,即使 A B 是相关的,对吗?

std::shared_ptr<A> and std::shared_ptr<B> are different types even if A and B are related, right?

推荐答案

A std :: shared_ptr< T&当且仅当 U  * 时,code>可以从 std :: shared_ptr< U& >可隐式转换为 T  * 。查看 cppreference.com 上的构造函数超载(9)

A std::shared_ptr<T> is implicitly constructible from a std::shared_ptr<U> if and only if a U * is implicitly convertible to a T *. See the constructor overload (9) on cppreference.com.

这篇关于多态智能指针使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆