Reputation: 20774
Suppose I declare a function accepting an std::shared_ptr<const T>
argument:
void func(std::shared_ptr<const T> ptr);
Will this function accept calls where a std::shared_ptr<T>
is passed instead?
Upvotes: 0
Views: 655
Reputation: 3417
You can pass shared_ptr, but you will able to call only const methods:
void foo(std::shared_ptr<const A> val)
{
val->ConstMethod();
val->Method(); // Denied
}
//....
std::shared_ptr<A> a(new A());
foo(a);
Upvotes: 2
Reputation: 302852
If you look at the constructors for std::shared_ptr
, two of them are :
template< class Y >
shared_ptr( const shared_ptr<Y>& r ); // (9)
template< class Y >
shared_ptr( shared_ptr<Y>&& r ); // (10)
which
9) Constructs a
shared_ptr
which shares ownership of the object managed byr
. Ifr
manages no object,*this
manages no object too. This overload doesn't participate in overload resolution ifY*
is not implicitly convertible toT*
.10) Move-constructs a
shared_ptr
fromr
. After the construction,*this
contains a copy of the previous state ofr
,r
is empty. This overload doesn't participate in overload resolution ifY*
is not implicitly convertible toT*
.
These constructors are not explicit
, and T*
is definitely implicitly convertible to const T*
, that's just a qualification conversion. So yes, the function will accept it. Simple Demo
Upvotes: 2