将声明为“自动”的 std::shared_ptr<Derived> 传递给 std::shared_ptr<Base>&

问题描述

使用 g++ -std=c++11 -pedantic-errors -Wall -Wextra -g 编译

void foo(std::shared_ptr<Base>& ptr) {
    std::cout << "foo()\n";
    std::cout << "count = " << ptr.use_count() << "\n";     
}

int main(int argc,char* argv[]) {
    auto d = std::make_shared<Derived>(5);
    foo(d);

    return 0;
}

我收到以下错误

shared_ptr.cpp:47:10: error: cannot bind non-const lvalue reference of type ‘std::shared_ptr<Base>&’ to an rvalue of type ‘std::shared_ptr<Base>’
     foo(d);

如果我将 d 的声明更改为 std::shared_ptr<Base> d 代码编译。

我的问题是:是否所有带有 auto 的类型声明都会生成一个 r 值?

非常感谢有关此事的任何阅读材料, 谢谢

解决方法

是否所有带有 auto 的类型声明都会生成一个 r 值?

没有。这与这里无关。

d 是一个 std::shared_ptr<Derive>,但是 foo 接受 std::shared_ptr<Base>,那么它需要转换为 std::shared_ptr<Base>,它是一个临时对象(一个右值) 并且不能绑定到非常量的左值引用,即 std::shared_ptr<Base>&