2016-08-16 68 views
2

這裏是我的一段代碼:爲什麼我不能使用std :: unique_ptr來避免循環依賴?

class Model; 

class Resources 
{ 
public: 
    Resources() : 
     initialized(false) 
    , pathToSkyBoxModel("E:\\C++\\OpenGLtutorial\\resources\\cube.obj") 
{}; 

    void Init(const ShaderProgram& shaderProgram); 

    /* Setters */ 
    void SetSkyBoxModelPath(std::string&& newPath) { pathToSkyBoxModel = newPath; }; 

    /* Getters */ 
    bool IsInitialized() const noexcept { return initialized; }; 
    const std::string& GetPathToSkyBoxModel() const noexcept { return pathToSkyBoxModel; }; 

    DiffuseTexture default_texture; 
    TransparentTexture default_transparent_texture; 

    private: 

    std::unique_ptr<Model> pModel; 
    bool initialized; 
}; 

我試圖避免使用的std ::針對的unique_ptr資源類成員pModel循環依賴。不幸的是,我得到了編譯錯誤,如:「你不能在這裏使用部分定義的類」。但它適用於std :: shared_ptr和公共指針。 std :: unique_ptr有什麼問題?

+0

另一個重複定義它繞過它:?向前聲明用的unique_ptr(http://stackoverflow.com/questions/13414652/forward-declaration-with-unique-ptr) – iammilind

回答

4

問題是編譯器試圖聲明一個內聯析構函數,因此它需要類的完整定義。

您可以通過在.h聲明析構函數,並在/.cpp

//in .h 
~Resources(); 

//in cpp 
Resources::~Resources() {} 
+0

但爲什麼它與std :: shared_ptr一起工作? –

+1

http://stackoverflow.com/questions/20985667/why-doesnt-stdshared-ptr-need-to-know-complete-type-if-its-constructed-from shared_ptr有一個額外的間接,所以你需要只有在實際構造/刪除對象時才知道完整類型。 –