将派生类的std :: shard_ptr转换为基类的shard_ptr

convert std::shard_ptr of derived class to that of base class

本文关键字:ptr shard 基类 转换 std 派生      更新时间:2023-10-16
#include <iostream>
#include <memory>
class Base{
};
class Derive : public Base{
};
void foo(std::shared_ptr<Base>& p){
}
void bar(const std::shared_ptr<Base>& p){
}
int main(){
    auto base = std::make_shared<Base>();
    foo(base);
    bar(base);
    auto derive = std::make_shared<Derive>();
    foo(derive);
    bar(derive);
    return 0;
}

g -std = c 0x test.cpp

编译器说:

test.cpp:21:5: error: no matching function for call to 'foo'
    foo(derive);
    ^~~
test.cpp:9:6: note: candidate function not viable: no known conversion from 'std::__1::shared_ptr<Derive>' to
      'std::shared_ptr<Base> &' for 1st argument
void foo(std::shared_ptr<Base>& p){

您可以解释为什么您不能将派生类的共享_ptr传递给foo(),而您可以将其传递给bar()接收共享_ptr的const reference

对不起,我的英语不好。谢谢。

调用 foo(derive)需要从 derive构建临时的 std::shared_ptr<Base>,并且非const lvalue-reference不能绑定到临时对象。要调用foo,您将需要构造一个可以传递到它的命名std::shared_ptr<Base>

auto derive = std::make_shared<Derive>();
std::shared_ptr<Base> b = derive;
foo(b);

bar(derive)很好,因为const引用可以与临时性结合。未命名的临时std::shared_ptr<Base>是由derive构建的,对该临时性的引用将传递给bar