c++ - std::shared_ptr 在按引用传递时如何跨类层次结构转换?

标签 c++ c++11 type-conversion shared-ptr implicit-conversion

查看 20.8.2.2 类模板 shared_ptr [util.smartptr.shared] 我意识到 std::shared_ptr具有允许从 shared_ptr<Derived> 转换的模板复制构造函数和赋值运算符至 shared_ptr<Base>当且仅当 Derived*可转换为 Base* .这些转换(以我的理解)仅通过模板化的复制构造函数和赋值运算符完成。但是,似乎我也可以通过 shared_ptr<Derived>到采用 shared_ptr<Base>& 的函数(即,通过引用传递)。似乎应该有一个隐式转换运算符,但根据标准没有。

下面的代码阐明了我的意思:

#include <iostream>
#include <memory>

struct Base {};
struct Derived: Base {};

void f(const std::shared_ptr<Base>& ) {}

int main()
{
    std::shared_ptr<Derived> spDerived(new Derived);

    // conversion below is OK, via template copy ctor
    std::shared_ptr<Base> spBase(spDerived); 
    // also OK, via template copy assignment operator
    spBase = spDerived; 

    // why is this OK? Cannot see any conversion operators in
    // 20.8.2.2 Class template shared_ptr [util.smartptr.shared]
    f(spDerived); 
}

我的问题:在这种情况下,谁在执行来自 shared_ptr<Derived> 的转换?至 shared_ptr<Base>在通话中f(spDerived) ? (对于编译器 shared_ptr<Derived>shared_ptr<Base> 没有任何关系,即使 DerivedBase 的 child )

最佳答案

临时文件是通过模板复制构造函数创建的,该拷贝就是所引用的。 ctor 是隐式的,因此在这种情况下可以合法地调用它。从根本上说,此调用与 f(std::string); 之间没有区别。 f("你好");。完全相同的机制在起作用。这是一个常规的隐式转换。

关于c++ - std::shared_ptr 在按引用传递时如何跨类层次结构转换?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29723938/

相关文章:

c++ - QT中如何修改键盘输入?

c++ - 为什么分配器常量在 vector 中?

c++ - 为什么重载的移动赋值运算符返回左值引用而不是右值引用?

python - 如何将 2D 字符串列表转换为 2D int 列表 python?

android - 保存位图的 RGB

c++ - 为什么 constexpr 不会因索引越界而导致编译失败

c++ - 如何将某个类的指针方法转换为指针函数?

c++ - 设置获取元素的位置

c++ - C++14 中纯右值的 Cv 限定

Python:获取类型并转换为这种类型