a06e
a06e

Reputation: 20774

Is there an implicit conversion from std::shared_ptr<T> to std::shared_ptr<const T>?

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

Answers (2)

Eugene
Eugene

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

Barry
Barry

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 by r. If r manages no object, *this manages no object too. This overload doesn't participate in overload resolution if Y* is not implicitly convertible to T*.

10) Move-constructs a shared_ptr from r. After the construction, *this contains a copy of the previous state of r, r is empty. This overload doesn't participate in overload resolution if Y* is not implicitly convertible to T*.

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

Related Questions