【发布时间】:2014-09-19 02:54:40
【问题描述】:
将shared_ptr<Derived>& 传递为shared_ptr<Base>& 时出现编译错误,请参阅下面的代码和详细问题。
注意:此问题与“Passing shared_ptr<Derived> as shared_ptr<Base>”类似,但不重复。
#include <memory>
class TBase
{
public:
virtual ~TBase() {}
};
class TDerived : public TBase
{
public:
virtual ~TDerived() {}
};
void FooRef(std::shared_ptr<TBase>& b)
{
// Do something
}
void FooConstRef(const std::shared_ptr<TBase>& b)
{
// Do something
}
void FooSharePtr(std::shared_ptr<TBase> b)
{
// Do something
}
int main()
{
std::shared_ptr<TDerived> d;
FooRef(d); // *1 Error: invalid initialization of reference of type ‘std::shared_ptr<TBase>&’ from expression of type ‘std::shared_ptr<TDerived>’
FooConstRef(d); // *2 OK, just pass by const reference
FooSharePtr(d); // *3 OK, construct a new shared_ptr<>
return 0;
}
由g++ -std=c++11 -o shared_ptr_pass_by_ref shared_ptr_pass_by_ref.cpp编译
环境:Ubuntu 14.04,g++ (Ubuntu 4.8.2-19ubuntu1) 4.8.2
详细问题: 为什么通过 const 引用(*2)可以传递,但不能通过引用(*1)传递?
注意:我知道最好的做法是通过 const 引用传递,但只是想知道为什么会出现编译错误。
【问题讨论】:
-
如果
FooRef做b.reset(new TBase)怎么办?如果可以调用,您最终会得到std::shared_ptr<TDerived>持有TBase*。顺便说一句,我怀疑FooConstRef调用构造了一个临时的,然后绑定到 const 引用;但是临时对象不能绑定到非常量引用。 -
好点!我会接受这个答案
标签: c++ inheritance c++11 casting shared-ptr