c++11 - shared_ptr<T> 到 const shared_ptr<const T>&

标签 c++11 shared-ptr implicit-conversion pass-by-const-reference reference-binding

我对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/

相关文章:

c++ - 是否有推荐的方法来测试智能指针是否为空?

c++ - 通过引用或按值将共享指针作为参数传递给类

c - 隐式类型转换的意外结果

c# - 隐式转换不可分配给接口(interface)

c++ - 隐式转换限制

c++ - 类的预制实例

c++ - 具有单个成员(也是自定义结构)的自定义结构(包装器)的集合,到单个成员的集合

c++ - 为什么 std::shared_ptr 不使用引用链接?

c++ - 返回对类的引用

c++ - 继承类对象的析构执行