Shared_ptr <T> for const shared_ptr <const T>
I am confused about shared_ptr and my main question is: does C ++ create a new object (shared_ptr object) when I do the following?
void Func1(const shared_ptr<T>& rhs) {}
void Func2(const shared_ptr<const T>& rhs) {}
shared_ptr<T> v1;
Func1(v1);
Func2(v1);
It is clear that it Func1(v1)
is transmitted by ref. However, what about Func2(v1)
?
Will the violator do the following:
shared_ptr<const T> tmp_v2 = v1;
Func2(tmp_v2);
I take care of this because it Func2
might cost more time (if it creates a new shared_ptr) than Func1
.
Many thanks for your help!
Nothing magic here, it's just one of the shared_ptr
constructor overloads (number 9)
template< class Y >
shared_ptr( const shared_ptr<Y>& r );
9) Creates a
shared_ptr
, which shares ownership of the object controlled by r. If r does not control any object, that also does not control the object. Template overloading is not involved in overload resolution if Y is implicitly convertible to (pre-C ++ 17) compatible with (since C ++ 17) T *.
For this to work, const T
must be implicitly convertible from T
, no other object will be created , only the other will be managed shared_ptr
.