如何使用可选值初始化shared_ptr映射

时间:2012-07-30 10:18:20

标签: c++ boost

我正在尝试使用包含可选值的地图初始化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'不提供下标运算符。

任何人都知道可能是什么问题?

1 个答案:

答案 0 :(得分: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) 作为构造函数不修改它:

{{1}}