2012-07-30 34 views
1

我想用具有可選值的映射初始化shared_ptr。我將在程序的後期階段初始化這些值。如何使用可選值初始化shared_ptr映射

我讀了下面的帖子,並用它作爲指導:How to add valid key without specifying value to a std::map?

但是我的情況有點不同,因爲我使用一個shared_ptr。事不宜遲,這是我寫的代碼:

ShaderProgram.h

... 
#include <map> 
#include <boost/shared_ptr.hpp> 
#include <boost/optional.hpp> 

typedef map<string, optional<GLuint> > attributes_map; 

class ShaderProgram 
{ 
public: 
    ShaderProgram(vector<string> attributeList); 
    ... 
private: 
    shared_ptr<attributes_map> attributes; 
}; 

ShaderProgram.mm

ShaderProgram::ShaderProgram(vector<string> attributeList) 
{ 
    // Prepare a map for the attributes 
    for (vector<string>::size_type i = 0; i < attributeList.size(); i++) 
    { 
     string attribute = attributeList[i]; 
     attributes[attribute]; 
    } 
} 

編譯器會通知我,以下錯誤:類型 'shared_ptr的' 不提供一個下標操作符。

任何想法可能是什麼問題?

回答

4

attributesshared_ptr並且沒有operator[]但是map。您需要取消對它的引用:

(*attributes)[attribute]; 

注意沒有map對象在構造函數中被分配給attributes所以一旦編譯器錯誤得到解決,你會得到一些描述運行時出現故障。無論分配map實例:

ShaderProgram::ShaderProgram(vector<string> attributeList) : 
    attributes(std::make_shared<attributes_map>()) 
{ 
    ... 
} 

或不使用shared_ptr,如爲什麼在這種情況下,需要進行動態分配不是很明顯:

private: 
    attributes_map attributes; 

通過引用傳遞attributeList避免不必複製,因爲const作爲構造函數不會修改它:

ShaderProgram::ShaderProgram(const vector<string>& attributeList) 
+0

@LucDanton,同意和更新。 – hmjd 2012-07-30 10:36:38

+0

感謝運行時錯誤的擡頭;) – polyclick 2012-07-30 11:01:31