2015-06-09 26 views
0

我有一個類VectorSpace與成員createVector()它創建一個帶有指向VectorSpace的共享指針的Vector。這通過std::enable_shared_from_this來實現。std :: enable_shared_from_this:沒有已知的從a到a的轉換

然而,這下面的代碼

#include <memory> 

class Vector; 
class VectorSpace; 

class Vector { 
public: 
    Vector(std::shared_ptr<VectorSpace> & space): 
    space_(space) 
    { 
    }; 

private: 
    std::shared_ptr<VectorSpace> space_; 
}; 

class VectorSpace: std::enable_shared_from_this<VectorSpace> { 
    public: 
    VectorSpace(){}; 

    Vector 
    createMember() 
    { 
    return Vector(shared_from_this()); 
    }; 

}; 

int main() { 
    auto space = std::make_shared<VectorSpace>(); 
    Vector x(space); 
} 

失敗與和非常奇怪的錯誤消息

test.cpp:8:3: note: no known conversion for argument 1 from ‘std::shared_ptr<VectorSpace>’ to ‘std::shared_ptr<VectorSpace>’ 

(這與GCC 4.9.2。)

編譯這裏的交易是什麼?

+2

嘗試刪除&在向量構造函數:shared_from_this創建新的shared_ptr – Hcorg

+0

@Hcorg剛剛注意到您的評論。你可能會考慮讓這類事情成爲答案 - 它解決了這個問題。 –

+1

我可以告訴你編輯了錯誤信息,因爲你沒有顯示錯誤。您僅在錯誤中複製** note **。請不要隱藏錯誤消息。他們不應該是祕密! – Yakk

回答

3

問題就在這裏:

Vector(std::shared_ptr<VectorSpace> & space): 
            ^^^ 

Vector構造函數有一個左參考,但在createMember()你傳遞一個右值:

Vector 
    createMember() 
    { 
    return Vector(shared_from_this()); 
    }; 

剛落&。對於它的價值,我沒有獲得GCC 4.9.2,但是5.1.0至少錯誤消息是相當清楚的:

main.cpp: In member function 'Vector VectorSpace::createMember()': 

main.cpp:24:35: error: invalid initialization of non-const reference of type 'std::shared_ptr<VectorSpace>&' from an rvalue of type 'std::shared_ptr<VectorSpace>' 

    return Vector(shared_from_this());  
           ^

代碼中的第二個問題是:

class VectorSpace: std::enable_shared_from_this<VectorSpace> { 

由於Angew指出,您需要公開繼承enable_shared_from_this

+0

現在它說:'錯誤:'std :: enable_shared_from_this '是一個'VectorSpace''的人跡罕至的基地。這對GCC 5.1有什麼不同? –

+4

@NicoSchlömer您需要爲'enable_shared_from_this'使用公共繼承。 – Angew

相關問題