C++ 如何使用可选值初始化共享\u ptr映射

C++ 如何使用可选值初始化共享\u ptr映射,c++,boost,C++,Boost,我试图用一个具有可选值的映射初始化一个共享的\u ptr。我将在程序的稍后阶段初始化这些值 我阅读了下面的帖子并将其作为指南: 但我的情况有点不同,因为我使用的是共享的ptr。不用多说,这就是我写的代码: 着色器程序 ... #include <map> #include <boost/shared_ptr.hpp> #include <boost/optional.hpp> typedef map<string, optional<GLuint

我试图用一个具有可选值的映射初始化一个共享的\u ptr。我将在程序的稍后阶段初始化这些值

我阅读了下面的帖子并将其作为指南:

但我的情况有点不同,因为我使用的是共享的ptr。不用多说,这就是我写的代码:

着色器程序

...
#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;
};
。。。
#包括
#包括
#包括
typedef映射属性_映射;
类着色器程序
{
公众:
着色器程序(向量属性列表);
...
私人:
共享的ptr属性;
};
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];
    }
}
ShaderProgram::ShaderProgram(向量属性列表)
{
//准备属性的映射
对于(vector::size_type i=0;i
编译器通知我以下错误:类型“shared_ptr”未提供下标运算符


有人知道问题出在哪里吗?

属性
是一个
共享的\u ptr
,没有
操作符[]
,但有
映射
。您需要取消对它的引用:

(*attributes)[attribute];
注意:构造函数中没有为
属性
分配
映射
对象,因此一旦编译器错误得到解决,您将得到某种描述的运行时故障。分配一个
map
实例:

ShaderProgram::ShaderProgram(vector<string> attributeList) :
    attributes(std::make_shared<attributes_map>())
{
    ...
}
通过引用传递
attributeList
,以避免不必要的复制,并作为
const
传递,因为构造函数不修改它:

ShaderProgram::ShaderProgram(const vector<string>& attributeList)
ShaderProgram::ShaderProgram(常量向量和属性列表)

属性
是一个
共享的ptr
,没有
操作符[]
,但有一个
映射
。您需要取消对它的引用:

(*attributes)[attribute];
注意:构造函数中没有为
属性
分配
映射
对象,因此一旦编译器错误得到解决,您将得到某种描述的运行时故障。分配一个
map
实例:

ShaderProgram::ShaderProgram(vector<string> attributeList) :
    attributes(std::make_shared<attributes_map>())
{
    ...
}
通过引用传递
attributeList
,以避免不必要的复制,并作为
const
传递,因为构造函数不修改它:

ShaderProgram::ShaderProgram(const vector<string>& attributeList)
ShaderProgram::ShaderProgram(常量向量和属性列表)