c++11shared-ptrimplicit-conversionpass-by-const-referencereference-binding

shared_ptr<T> to const shared_ptr<const T>&


I feel 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);

Clearly, Func1(v1) is passed by ref. However, how about Func2(v1) ?

Will the complier does the following thing behind?

shared_ptr<const T> tmp_v2 = v1;
Func2(tmp_v2);

I care about it, because Func2 may cost more time (if it does create a new shared_ptr object) than Func1.

Thanks very much for your help!


Solution

  • There isn't anything magical here, it's just one of the shared_ptr constructor overload (number 9)

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

    9) Constructs a shared_ptr which shares ownership of the object managed by r. If r manages no object, this manages no object too. The template overload doesn't participate in overload resolution if Y is not implicitly convertible to (until C++17)compatible with (since C++17) T*.

    In order for that to work, const T has to be implicitly convertible from T, another object will not be created, only be managed by another shared_ptr.