C++ 将派生类的std::shard_ptr转换为基类的std::shard_ptr #包括 #包括 阶级基础{ }; 类派生:公共基{ }; 无效foo(标准::共享的ptr&p){ } 空栏(const std::shared_ptr&p){ } int main(){ auto base=std::make_shared(); 富(基地);; 杆(底座); 自动派生=标准::使_共享(); foo(派生); 酒吧(衍生); 返回0; }

C++ 将派生类的std::shard_ptr转换为基类的std::shard_ptr #包括 #包括 阶级基础{ }; 类派生:公共基{ }; 无效foo(标准::共享的ptr&p){ } 空栏(const std::shared_ptr&p){ } int main(){ auto base=std::make_shared(); 富(基地);; 杆(底座); 自动派生=标准::使_共享(); foo(派生); 酒吧(衍生); 返回0; },c++,c++11,pointers,inheritance,shared-ptr,C++,C++11,Pointers,Inheritance,Shared Ptr,g++-std=c++0x test.cpp 编者说: #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

g++-std=c++0x test.cpp

编者说:

#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;
}
test.cpp:21:5:错误:调用'foo'没有匹配的函数
foo(派生);
^~~
test.cpp:9:6:注意:候选函数不可行:没有已知的从“std::_1::shared_ptr”到
第一个参数的“std::shared_ptr&”
无效foo(标准::共享的ptr&p){
您能否解释一下为什么不能将派生类的共享\u ptr传递给foo(),而可以将其传递给接收共享\u ptr的常量引用的bar()

对不起,我的英语很差。 谢谢。

调用
foo(派生)
需要从
派生
构造一个临时的
std::shared\u ptr
,非常量左值引用不能绑定到临时对象。要调用
foo
,您需要构造一个命名的
std::shared\u ptr
,您可以将其传递给它:

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){
auto-derivate=std::make_shared();
std::shared_ptr b=派生;
傅(乙);;

条(派生)
很好,因为常量引用可以绑定到临时变量。未命名的临时变量
std::shared_ptr
derivate
构造,对该临时变量的引用被传递到
bar

这是临时变量的终身扩展。我确信这是现有问题的重复,可能有助于您获得它t:通常不应通过非
const
引用传递
std::shared_ptr
,因为如果将智能指针传递给派生类,则从函数内部修改指针没有多大意义。
auto derive = std::make_shared<Derive>();
std::shared_ptr<Base> b = derive;
foo(b);