我对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
花费更多的时间(如果它确实创建了一个新的 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
管理.
关于c++11 - shared_ptr<T> 到 const shared_ptr<const T>&,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43027186/