2014-03-28 29 views
1

所以我有一些代碼:爲什麼我不能返回nullptr std :: weak_ptr?

class Thing 
{ 
public: 
    Thing() = default; 
}; 

class DbOfThings 
{ 
public: 
    DbOfThings() = default; 

    std::weak_ptr<Thing> GetEntry(int someKey) const 
    { 
     // returns a weak_ptr from mThings, or null if a Thing 
     // that has someKey was not found 
     return std::weak_ptr<Thing>(nullptr); 
    } 
private 
    // Idea is that this object owns these things, but other objects can grab a thing from here - but the thing can be killed off at any time 
    std::vector<std::share_ptr<Thing>> mThings; 

但這種失敗,編譯:

沒有已知的轉換爲參數1從 '的std :: nullptr_t' 到「常量 的std :: weak_ptr的& '

爲什麼?我是否願意讓其他對象擁有另一個錯誤所擁有的東西?這對於weak_ptr來說似乎是一個有效的用例。我該如何做這項工作?

+0

似乎沒有這樣的構造,但你可以使用默認的:'返回{};' – zch

+0

爲什麼要用'shared_ptr'而不是'unique_ptr'如果向量是擁有該對象的唯一的事情嗎? (或者你可以不爲'unique_ptr'擁有的對象創建'weak_ptr',即使弱指針不會導致指向對象的所有權發生變化?) – JAB

+0

...哦,我明白了。因爲'shared_ptr'可以將'weak_ptr'作爲構造函數,允許指向唯一指針所擁有的對象的弱指針將需要終止唯一指針,儘管'shared_ptr'有一個'unique_ptr'構造函數,可以間接地做到這一點有奇怪的效果。 – JAB

回答

7

weak_ptr不具有采取nullptr_t或裸指針任何constructors,所以你不能構建一個與nullptr作爲參數。要獲得一個空的weak_ptr只是默認構造一個。

std::weak_ptr<Thing> GetEntry(int someKey) const 
{ 
    // returns a weak_ptr from mThings, or null if a Thing 
    // that has someKey was not found 
    return std::weak_ptr<Thing>(); 
    // or 
    // return {}; 
} 
+0

這樣的構造函數唯一可以使用的就是取一個空指針。對於任何其他指針都沒有明智的語義。 –

+0

該死的 - 我敢肯定,當我這樣做時,我有一個編譯器錯誤,但是這是有效的! – paulm

相關問題