是否存在从 std::shared_ptr<T> 到 std::shared_ptr<const T> 的隐式转换?

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

假设我声明一个接受 std::shared_ptr<const T> 参数的函数:

void func(std::shared_ptr<const T> ptr);

此函数会接受传递 std::shared_ptr<T> 的调用吗?

如果您查看 std::shared_ptr 的构造函数,其中两个是:

template< class Y > 
shared_ptr( const shared_ptr<Y>& r );  // (9)

template< class Y > 
shared_ptr( shared_ptr<Y>&& r );       // (10)

哪个

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*.

这些构造函数不是explicitT*肯定可以隐式转换为const T*,那只是限定转换。所以是的,函数会接受它。 Simple Demo

您可以传递 shared_ptr,但您将只能调用常量方法:

void foo(std::shared_ptr<const A> val)
{
    val->ConstMethod();
    val->Method();      // Denied
}

//....
std::shared_ptr<A> a(new A());

foo(a);