简体   繁体   中英

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?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM