傳遞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