2016-07-04 37 views
-1

所以我使用SFML和Boost庫試圖編寫一個ResourceManager類。我使用std :: map來包含資源。我最近聽說std :: unique_ptr真的很好,因爲它的內存清理(或其他方面)。std :: unique_ptr實例化錯誤試圖放在std :: map內?

這是我的ResourceManager類的樣子:

#pragma once 

#include <boost/Any.hpp> 
#include <map> 
#include <memory> 
#include <SFML/Graphics.hpp> 

#include "Resource.h" 


class ResourceManager 
{ 
    public: 
     ResourceManager(); 
     void clear(); 
     void dump(); 
     boost::any getResource(std::string s); 
     sf::Texture loadTexture(std::string s, sf::IntRect d); 
     void unloadTexture(std::string s); 

    private: 
     std::map<std::string, std::unique_ptr<boost::any>> resource; 
}; 

這裏是我試圖使用對象加載到我的地圖的方法

sf::Texture ResourceManager::loadTexture(std::string s, sf::IntRect d) 
{ 
    std::unique_ptr<sf::Texture> t; 

    if (!t->loadFromFile(s, d)) 
     std::cout << "Error loading resource: " << s << std::endl; 

    resource[s] = t; 
} 

但是我得到這個錯誤在這裏這條線:http://i.imgur.com/0uDZvvw.png

+0

嘆了口氣,我以爲我只是被我如何使用unique_ptr而被推遲。我沒有確切的指導,但我會更新我的帖子更好地描述我的問題。給我幾分鐘<3 – Honor

+0

不,那不是你怎麼做的。如果沒有動態內存分配,那麼'unique_ptr'沒有意義。另外,當你*找到一個真正的用例時,請查看'std :: make_unique'。也許你應該描述*你想要做什麼,而不是*你目前正在做什麼。 –

+1

那麼,猜測編程不起作用。讓我們不要使用像「智障」這樣令人厭惡的,不光彩的詞彙,呃? –

回答

1

std::unique_ptr是一個移動的時間,這意味着你不能複製它。

要修復它,用std::move

resource[s] = std::move (t); 

如果能像你這樣複製的,那麼你就必須指向同一個物體的兩個unique_ptr的(這是無感,因爲他們是獨特的),所以你必須移動它,調用移動賦值運算符。

+0

啊哈!就是這樣,非常感謝!我會贊成但不再有15代表以上; - ; – Honor

+0

@榮譽,如果答案回答你的問題,你應該將其標記爲。 – 2016-07-05 14:19:38