[英]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 byr
.9)构造一个
shared_ptr
,它共享由r
管理的对象的所有权。 Ifr
manages no object,*this
manages no object too.如果
r
管理任何对象,则*this
也不管理任何对象。 This overload doesn't participate in overload resolution ifY*
is not implicitly convertible toT*
.如果
Y*
不能隐式转换为T*
则此重载不参与重载解析。10) Move-constructs a
shared_ptr
fromr
.10)从
r
移动构造一个shared_ptr
。 After the construction,*this
contains a copy of the previous state ofr
,r
is empty.构造之后,
*this
包含r
先前状态的副本,r
为空。 This overload doesn't participate in overload resolution ifY*
is not implicitly convertible toT*
.如果
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.