2012-12-09 29 views
1

所以,這裏是我的類及其功能:的boost :: shared_ptr的和nullptr預設模板函數參數

template <class T> 
class cResourceManager 
{ 
public: 
    bool add(const std::string & key, boost::shared_ptr<T> ptr = nullptr); 
private: 
    std::map <const std::string, boost::shared_ptr<T> > resources; 
}; 

template <class T> 
bool cResourceManager<T>::add(const std::string & key, boost::shared_ptr<T> ptr) 
{ 
    if (resources.find(key) == resources.end()) 
    { 
     if(ptr != nullptr) //we have the object 
     { 
      resources.insert(std::pair<const std::string, boost::shared_ptr<T>>(key, ptr)); 
     return true; 
    } 
    else //we need to load object using sfml loadFromFile 
    { 
     T tempResource; 
     tempResource.loadFromFile(key); 
     resources.insert(std::pair<const std::string, boost::shared_ptr<T>>(key, new T(tempResource))); 
     if(resources[key] == nullptr) return false; 
     else return true; 
    } 
} 
}  

這個類是靜態庫,它compliles沒有問題。然而,當我使用它在正常的應用程序:

cResourceManager<sf::Texture> resourceManager; 
resourceManager.add("1.PNG"); 

我得到錯誤: 錯誤:類型的參數默認參數 '的boost :: shared_ptr的' 有型 '的std :: nullptr_t'

我不知道這裏有什麼問題,不能shared_ptr有nullptr值? 我使用g ++ 4.7和-std = C++ 11

謝謝!

回答

2

這將工作中std :: shared_ptr的,而不是升壓:: shared_ptr的,我認爲

+0

shared_ptr現在在C++ 11標準中了嗎?第二個問題,做boost :: shared_ptr有一些nullptr關鍵字? – user1873947

2

http://www.boost.org/doc/libs/1_52_0/libs/smart_ptr/shared_ptr.htm#Membersboost::shared_ptr不能由一個空指針,因爲指針,以構造常數初始化,它是由Y*模板Y是模板參數。在推導出Y*時,不會考慮將空指針常量轉換爲Y*,以便構造函數將具有推導失敗並在通過nullptr時被忽略。

std::shared_ptr可以接受它,因爲它有一個std::nullptr_t過載,所以如果你想,你可以切換。

請注意,通過nullptr不同於傳遞空指針,如(T*)nullptr。後者不會使用構造函數constexpr,但前者將會(除其他差異之外)。所以在前一種情況下,如果你的指針是一個命名空間範圍變量,它就會有不斷的初始化,並且不會在其他翻譯單元中引發具有命名空間範圍對象的初始化競爭。

+0

謝謝!所以我會切換到std :: shared_ptr – user1873947

+0

@ user1873947或者你可以傳遞一個默認構造的'boost :: shared_ptr'或者在C++ 11中(這是使用'std :: shared_ptr'的前提條件),你可以通過''}'作爲函數參數,如果你想避免把'boost :: shared_ptr'的所有實例改爲'std :: shared_ptr'。 –

+0

我將完全切換到std :: shared_ptr。但是,什麼是與std :: shared_ptr聲明文件?我找不到它,我得到「std :: shared_ptr」沒有被聲明「 – user1873947

3

Boost :: shared_ptr將從版本1.53開始支持來自std :: nullptr_t的構造函數。