2013-03-12 28 views
-2

我不明白爲什麼下面的代碼在編譯時失敗,並返回「臨時引用」。對我來說,單身不能是暫時的,因爲它是靜態的!?C++奇怪的引用臨時

感謝

#include <memory> 

class Parent { 
public: 
    static const std::shared_ptr<Parent>& get_default_value(); 
    static const std::shared_ptr<Parent>& get_some_other_value(); 
}; 

class Child: public Parent { 
public: 
    Child(){} 
    static const std::shared_ptr<Child>& singleton; 
}; 

const std::shared_ptr<Child>& singleton = std::make_shared<Child>(); 

const std::shared_ptr<Parent>& Parent::get_default_value() { 
    return singleton; 
} 

const std::shared_ptr<Parent>& Parent::get_some_other_value() { 
    //FILL ME 
} 

Proof

編輯:家長的默認值是孩子的單身人士。 (之前還有一些其他的名字,但這令人困惑)。

編輯2:我也想有shared_pointers引用,因爲默認情況經常發生,是一個單身不管怎麼說,這樣一個還不如節省空間

編輯3:我想一個std :: shared_ptr的&作爲類型結果,因爲我希望界面對於默認值和其他值保持一致

編輯4:由於不相關的原因,其他值需要爲shared_ptr <>。

+4

爲什麼你需要將引用傳遞給周圍的共享指針? – James 2013-03-12 17:48:53

+2

您的目標是要返回「Child」單身人士還是全球單身人士? – chrisaycock 2013-03-12 17:55:05

+0

爲什麼你想要一個'shared_ptr'給單身人士?通常情況下,我期望getter返回一個引用。 – 2013-03-12 17:59:25

回答

4

您的問題是Child::singleton類型爲std::shared_ptr<Child>&get_singleton回報std::shared_ptr<Parent>&的。 std::shared_ptr<Child>可以轉換爲std::shared_ptr<Parent>而不是std::shared_ptr<Parent>&,因此它必須創建一個類型爲std::shared_ptr<Parent>的臨時對象並返回對該對象的引用。

無論如何,通常沒有理由通過引用返回shared_ptr。只需返回值,它會編譯。在從德克分析,轉換的問題

2

沒有哪個單身人士是你臨時宣佈的方式。聲明靜態變量:

const std::shared_ptr<Child>& Child::singleton = std::make_shared<Child>(); 

注意Child::?另外在功能get_singleton用途:

const std::shared_ptr<Parent>& Parent::get_singleton() { 
    return Child::singleton; 
} 
+0

這不可能是原因。 [證明](http://stacked-crooked.com/view?id=fc247c19cd5e0233e518ec330a3b6448-18aa934a8d82d638dde2147aa94cac94) – 2013-03-12 17:56:51

0

大廈,這是一個很好的解決方案:

class Parent { 
public: 
    static const std::shared_ptr<Parent>& get_singleton(); 
}; 

class Child: public Parent { 
public: 
    Child(){} 
    static const std::shared_ptr<Parent>& singleton; 
}; 

const std::shared_ptr<Parent>& singleton = std::make_shared<Child>(); 

const std::shared_ptr<Parent>& Parent::get_singleton() { 
    return singleton; 
} 

Proof