简体   繁体   English

从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>?

Suppose I declare a function accepting an std::shared_ptr<const T> argument: 假设我声明了一个接受std::shared_ptr<const T>参数的函数:

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

Will this function accept calls where a std::shared_ptr<T> is passed instead? 此函数将接受通过std::shared_ptr<T>传递的调用吗?

If you look at the constructors for std::shared_ptr , two of them are : 如果查看std::shared_ptr的构造函数,则其中两个是:

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 . 9)构造一个shared_ptr ,它共享由r管理的对象的所有权。 If r manages no object, *this manages no object too. 如果r管理任何对象,则*this也不管理任何对象。 This overload doesn't participate in overload resolution if Y* is not implicitly convertible to T* . 如果Y*不能隐式转换为T*则此重载不参与重载解析。

10) Move-constructs a shared_ptr from r . 10)从r移动构造一个shared_ptr After the construction, *this contains a copy of the previous state of r , r is empty. 构造之后, *this包含r先前状态的副本, r为空。 This overload doesn't participate in overload resolution if Y* is not implicitly convertible to T* . 如果Y*不能隐式转换为T*则此重载不参与重载解析。

These constructors are not explicit , and T* is definitely implicitly convertible to const T* , that's just a qualification conversion. 这些构造函数不是explicit ,并且T*绝对可以隐式转换为const T* ,这只是一个条件转换。 So yes, the function will accept it. 所以是的,该函数将接受它。 Simple Demo 简单演示

You can pass shared_ptr, but you will able to call only const methods: 您可以传递shared_ptr,但您只能调用const方法:

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

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

foo(a);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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