2012-07-30 63 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