5

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!

curiousguy
  • 8,038
  • 2
  • 40
  • 58
JJ.
  • 111
  • 11

1 Answers1

2

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.

David Haim
  • 25,446
  • 3
  • 44
  • 78
  • "_const T has to be implicitly convertible from T_" what do you mean? – curiousguy Mar 26 '17 at 20:27
  • @curiousguy I think he means exactly what he said. The constructor requires that `Y` is implicitly convertible to `T`. In the OP's case `Y` is `T` and `T` is `const T`, so it requires that "T is implicitly convertible to const T" or in other words, "const T has to be implicitly convertible from T". Like he said. Luckily, const T is always convertible from T, so it works. – Jonathan Wakely Apr 04 '17 at 15:00