简体   繁体   中英

Const correctness and shared_ptr conversions

Let's say I have following types:

using pointer = std::shared_ptr<MyType>;
using pointer_to_const = std::shared_ptr<const MyType>;

Now, if I have piece of code like the following:

void fun(pointer_to_const ptr);

pointer myObj = SomeFactoryMethod();
fun(myObj);

Is there an automatic conversion between pointer and pointer_to_const ? And if there is, would the underlying MyType object be copied during this conversion?

Because if there is a conversion, and there's no copy, then in a multithreaded context another thread could use the original myObj pointer to modify the underlying object, thus violating the const which is expected by fun .

是的,这样的转换可以完成,并且将是指针和控制块的浅表副本(引用计数)。

Yes, this will work. Following constructor of shared_ptr will be called:

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

With Y deduced to be const MyType .

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