Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Polymorphic smart pointer usage

Tags:

c++

c++11

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);

Now when I got this:

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

Why it works again with

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

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

like image 740
Narek Avatar asked Dec 10 '22 20:12

Narek


1 Answers

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.

like image 173
5gon12eder Avatar answered Dec 13 '22 09:12

5gon12eder