shared_ptr<T> 到 const shared_ptr<const T>&

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

我对shared_ptr感到困惑,我的主要问题是:当我执行以下操作时,c++是否会创建一个新对象(shared_ptr对象)?

void Func1(const shared_ptr<T>& rhs) {}
void Func2(const shared_ptr<const T>& rhs) {}
shared_ptr<T> v1;
Func1(v1);
Func2(v1);

显然,Func1(v1) 由 ref 传递。但是,Func2(v1)呢?

编译器会不会在后面做下面的事情?

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

我很关心它,因为 Func2 可能比 Func1.[=33= 花费更多的时间(如果它确实创建了一个新的 shared_ptr 对象) ]

非常感谢您的帮助!

这里没有什么神奇的东西,它只是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*.

为了使其工作,const T 必须从 T 隐式转换,不会创建另一个对象 ,只能由另一个 shared_ptr.