传递shared_ptr<Derived>&
作为shared_ptr<Base>&
时出现编译错误,请参阅下面的代码和详细问题。传递shared_ptr时出错<Derived>&as shared_ptr <Base>&without const
注意:此问题与“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
的Env编译:Ubuntu的14.04,克++(Ubuntu的4.8.2-19ubuntu1)4.8.2
详细问题: 为什么行通过const引用传递(* 2),但不能通过引用(* 1)传递?
注:我知道最好的做法是通过const引用,但只是想知道为什么发生编译错误。
如果'FooRef'做了'b.reset(new TBase)'?如果可能的话,你最终会得到'std :: shared_ptr'拥有'TBase *'。顺便说一句,我怀疑'FooConstRef'调用构造一个临时的,然后绑定到const引用;但临时表不能绑定到非const参考。 –
2014-09-19 02:57:01
好点!我会接受这个答案 – Mine 2014-09-19 02:59:09